Here, there are two cins and to my understanding, each one leaves '\n' in the buffer because they skip whitespace.
Cin.ignore only skips one character by default so one of the '\n' is taken out. However, there is still one more '\n' in the buffer, so I would expect the getline to see the '\n' and getline to skip.
However, when I run this code, I am able to type into string3. Where am I going wrong?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string string1, string2, string3;
cout << "String1: ";
cin >> string1;
cout << "String2: ";
cin >> string2;
cin.ignore();
cout << "String3: ";
getline(cin, string3);
return 0;
}
cin >> string2
looks for the beginning of the next word, and skips over the newline that was left in the buffer aftercin >> string1
. So at this point ,only the second newline is still in the buffer, andcin.ignore()
skips past it.More detailed, if you type:
The buffer contains:
The
^
shows the current position in the buffer. At the beginning, it's at the beginning of the buffer. After you docin >> string1
, it looks like:When you do
cin >> string2
, it finds the beginning of the next word (the nextl
character), and after it's done the buffer looks like:Then
cin.ignore()
skips past the next newline, so it looks like:And now when you call
getline()
, it reads the line withline3
.