c++ - 为什么程序不能立即输出?

标签 c++

当我输入“111 111”然后按回车键时,输出没有任何显示。然后,当我按两次 enter 时,会出现预期的输出。这是为什么?

#include<iostream>
using namespace std;
int main()
{
    char seq[10];
    //initialize the sequence
    for (int i = 0; i<10; i++)
    {
        seq[i] = ' ';
    }
    //read characters from the keyboard
    for (int i = 0; i<10; i++)
    {
        cin.get(seq[i]);
        if (seq[i] == '\0')
        {
            break;
        }
    }
    //the output should be the sequence of characters
    //users typed before
    cout << seq;
    system("pause");
    return 0;
}

最佳答案

您可以改用头文件 string,它提供了更大的灵 active ,如下所示:

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string seq;
    //initialize the sequence

    //read characters from the keyboard
    getline(cin,seq);

    //the output should be the sequence of characters
    //users typed before
    cout << seq;
    system("pause");
    return 0;
}

回应 OP 的问题更新:

在所描述的情况下,您永远不会从标准输入中输入 \0,对吗?相反,您正在按回车键。

if (seq[i] == '\0'){

相反,您可以将此检查行替换为:

if (seq[i] == '\n'){

关于c++ - 为什么程序不能立即输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33852311/

相关文章:

c++ - 函数模板参数推导是否应该考虑转换运算符?

c++ - gcc 支持 cbegin 和 cend 方法

c++ - 无法从 Mac 上的 C++ 程序读取文件

c++ - 函数原型(prototype)中的 const

c++ - 条件为假时执行的 if 语句

c++ - 在 visual studio 中为 usertype.dat 中的关键字赋值?

c++ - Makefile vpath 不适用于头文件

c++ - 如何将对象实例转换为 shared_ptr 实例

c++ - Eclipse C++多个项目通用文件

c++ - 使用特定输入的 cuda/cublas 简单内核中的数值错误