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

Why can't the program output immidiately?

本文关键字:输出 程序 不能 为什么      更新时间:2023-10-16

当我输入"111 111"然后按enter键时,输出什么都不显示。然后,当我按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] == '')
        {
            break;
        }
    }
    //the output should be the sequence of characters
    //users typed before
    cout << seq;
    system("pause");
    return 0;
}

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

#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的问题更新:

在所描述的情况下,您从未从标准输入输入,对吧?相反,您是在按回车键。

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

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

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

您可以为std::getline()提供一个额外的char参数,用于定义行分隔符。在您的情况下,只需将其读到下一个''即可。

auto seq = std::string{};
std::getline(cin, seq, '');

顺便说一下:你真的确定吗,你想读到下一个''?用键盘输入一个零字符并不容易。如果您确实对输入中的完整行感兴趣,只需删除分隔符参数:std::getline(cin, seq)

此代码:

for (int i = 0; i<10; i++){
    seq[i] = ' ';
}

将seq中的所有元素初始化为空格,而不是"\0"。因此,我认为你的分手声明不会触发。

您的程序在执行其他操作之前读取10个字符。所以你需要提供10个字符。

中断检查从不触发。为什么?

最后,cout<lt;seq是不安全的,因为它可能在seq结束后读取内存。