0

The code I'm using is this:

string input;
cout<<"First line"<<endl;
cin>>input;
cout<<"second line: "<< input << endl;
getline(cin, input);
cout<<"third line: "<< input << endl;

However, when I input 54 say the output is this:

First line
>56
second line: 56
third line: 

and the program terminates without even asking for another input. This is weird as the following does work as expected:

string input;
cout<<"First line"<<endl;
getline(cin, input);
cout<<"second line: "<< input << endl;
getline(cin, input);
cout<<"third line: "<< input << endl;

i.e. input & output is:

First line
>56
second line: 56
>45
third line: 45
halfer
  • 18,701
  • 13
  • 79
  • 158
Yahya Uddin
  • 18,489
  • 26
  • 104
  • 189

2 Answers2

0

I believe the first example does not prompt for additional input because the >> operator does not consume the whitespace at the end of your first input (the newline character) and then the subsequent getline() call consumes that newline character and stops looking for more input.

If my hypothesis holds, then I think two calls to getline() ought to return first an empty string and then it will prompt for input.

SyntaxTerror
  • 236
  • 1
  • 10
0

The new line character remains in the stream after doing the cin>>input, which means that getline returns an empty string. You can try doing cin.ignore(std::numeric_limits<std::streamsize>::max()) or just cin.ignore() before the call to getline.

Simple
  • 12,634
  • 2
  • 38
  • 43