简体   繁体   中英

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:

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
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" .

To read an entire line:

getline(cin, input);

The buffer works OK. The logic behind opreator>> is ... ummm... a little bit complicated. You are in fact using a free standing operator>> for input stream and a string - 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).

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 .

It's worth to remember this nitpick too: Why does cin command leaves a '\\n' in the buffer?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM