当我输入“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/