How does cin.ignore work with cin and getline?

990 views Asked by At

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;
}
1

There are 1 answers

0
Barmar On BEST ANSWER

cin >> string2 looks for the beginning of the next word, and skips over the newline that was left in the buffer after cin >> string1. So at this point ,only the second newline is still in the buffer, and cin.ignore() skips past it.

More detailed, if you type:

line1
line2
line3

The buffer contains:

line1\nline2\nline3\n
^

The ^ shows the current position in the buffer. At the beginning, it's at the beginning of the buffer. After you do cin >> string1, it looks like:

line1\nline2\nline3\n
     ^

When you do cin >> string2, it finds the beginning of the next word (the next l character), and after it's done the buffer looks like:

line1\nline2\nline3\n
            ^

Then cin.ignore() skips past the next newline, so it looks like:

line1\nline2\nline3\n
              ^

And now when you call getline(), it reads the line with line3.