我正在尝试打印输入,然后打印 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/