gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:19:39 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com