[英]Strange cout behavior in a while loop in C++
I am trying to print the input and then all the strings in the tk vector, as in the following program: 我正在尝试打印输入内容,然后打印tk向量中的所有字符串,如以下程序所示:
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;
}
When I give the input "Hello world" I am expecting the output to be: 当我输入“ Hello world”时,我期望输出是:
Hello world
this
is
an
example
prompt:
But the output was: 但是输出是:
Hello
this
is
an
example
prompt: world
this
is
an
example
prompt:
Does anyone know what went wrong here? 有人知道这里出了什么问题吗? I guess the cause is related to how the buffer works, but I really have no idea about the details.
我想原因与缓冲区的工作方式有关,但是我真的不知道细节。
Streaming into a string with >>
reads a single word, up to a whitespace character. 用
>>
串流到一个字符串中会读取一个单词,直到一个空格字符。 So you get two separate inputs, "Hello"
and "world"
. 因此,您将获得两个单独的输入:
"Hello"
和"world"
。
To read an entire line: 要阅读整行:
getline(cin, input);
The buffer works OK. 缓冲区工作正常。 The logic behind
opreator>>
is ... ummm... a little bit complicated. opreator>>
背后的逻辑是……嗯……有点复杂。 You are in fact using a free standing operator>>
for input stream and a string - this no (2) . 实际上,您正在使用一个独立的
operator>>
作为输入流和一个字符串-this no(2) 。
The key part is: 关键部分是:
[...] then reads characters [...] until one of the following conditions becomes true:
[...]然后读取字符[...],直到满足以下条件之一:
[...]
[...]
std::isspace(c,is.getloc())
is true for the next character c in is (this whitespace character remains in the input stream).std::isspace(c,is.getloc())
对于in中的下一个字符c为true(此空白字符保留在输入流中)。
Which means it "eats" input until a white space (according to current locale) is met. 这意味着它会“吃掉”输入,直到满足空白(根据当前语言环境)。 Of course as Mike said, for the whole line, there is
getline
. 当然,正如迈克所说,整行都有
getline
。
It's worth to remember this nitpick too: Why does cin command leaves a '\\n' in the buffer? 还值得记住这个nitpick: 为什么cin命令在缓冲区中留下一个'\\ n'?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.