0

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.

user3724417
  • 373
  • 1
  • 3
  • 6
  • 4
    This comes up on SO daily. People keep forgetting (or they didn't read their C++ book properly!) that `>>` into a string gets _a word_. Surely there's a FAQ for this "problem"? – Lightness Races in Orbit Jan 28 '15 at 17:12
  • possible duplicate of [C++ cout cin string manipulation](http://stackoverflow.com/questions/1736080/c-cout-cin-string-manipulation) – Raymond Chen Jan 28 '15 at 19:11

2 Answers2

3

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);
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

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?

Community
  • 1
  • 1
luk32
  • 15,812
  • 38
  • 62