#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
. getline
is 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.
cin >> age;
The input buffer starts with a number, so we read 3
. Then we leave \n4\nBob\n
in the buffer.
cin >> Rollno;
Ignore leading whitespace (the newline) to get 4\nBob\n
. Now we see a number, so we read 4
and leave \nBob\n
.
At this point, using cin.getline
would be a mistake, as we would read only the newline character and then stop. So instead we
cin.ignore();
This ignores one character and leaves Bob\n
in the buffer.
getline(cin, name);
Now we read a line until we hit \n
. We consume the \n
but do not store it. So name
gets the value "Bob"
and the input buffer is now empty.