c++ - C++ 中 while 循环中的奇怪 cout 行为

标签 c++ iostream

我正在尝试打印输入,然后打印 tk vector 中的所有字符串,如以下程序所示:

int main() {
    while (true) {
        string input;
        cout << "prompt: ";
        cin >> input;
        vector<string> tk = {"this", "is", "an", "example"}; 

        cout << input << endl;
        for (int i = 0; i < tk.size(); i++) {
            cout << tk[i] << endl;
        }

    }   
    return 0; 
}

当我输入“Hello world”时,我期望输出为:

Hello world
this
is
an 
example
prompt: 

但是输出是:

Hello
this
is
an
example
prompt: world
this
is 
an
example
prompt:

有人知道这里出了什么问题吗?我猜原因与缓冲区的工作方式有关,但我真的不知道细节。

最佳答案

使用 >>> 流式传输到一个字符串中读取单个单词,直到一个空白字符。所以你得到两个独立的输入,"Hello""world"

阅读整行:

getline(cin, input);

关于c++ - C++ 中 while 循环中的奇怪 cout 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28198104/

相关文章:

c++ - Windows中有没有办法知道进程是否没有响应?

c++ - 可移植设备的 Windows 句柄

c++ - Visual Studio 2010 O2 优化给出错误的结果?

c++ - ostream& operator<< 没有 flush() 的段错误

c++ - 为什么 sleep() 会阻塞 std::ostream

c++ - 左右对齐输出一致

c++ - 尽管有线程,Qt GUI 仍挂起

c++ - 如何使用 char 数组字母表使用仿射密码对文本进行编码?

c++ - 杀死一个阻塞的 Boost::Thread

c++ - 如何使动态字符串在控制台中使用 UTF-8?