#include<iostream>
#include<cstring>
using namespace std;
int main(){
string name;
int age, Rollno;
cin >> age;
cin >> Rollno;
cin.ignore();
getline(cin, name);
cout << name << " " << age << " " << Rollno;
}
After entering a value for age using cin, a newline character remains in the input buffer. Despite this, how does the subsequent cin >>Rollno; successfully read the input for Rollno without any issues? Additionally, why is cin.ignore(); necessary before using getline(cin, name); and not necessary before cin>>Rollno; in this code?
Most of the parsers for
cin(such as the one that looks for integers, as you're using) will happily ignore leading whitespace, and this includes vertical whitespace like\n.getlineis not a parser; it simply gives you raw information without looking at it, so it has no such luxury.Suppose our input is
3\n4\nBob\n. Then we run your code.The input buffer starts with a number, so we read
3. Then we leave\n4\nBob\nin the buffer.Ignore leading whitespace (the newline) to get
4\nBob\n. Now we see a number, so we read4and leave\nBob\n.At this point, using
cin.getlinewould be a mistake, as we would read only the newline character and then stop. So instead weThis ignores one character and leaves
Bob\nin the buffer.Now we read a line until we hit
\n. We consume the\nbut do not store it. Sonamegets the value"Bob"and the input buffer is now empty.