How Does input Buffer actually works in C++?

106 Views Asked by At
#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?

2

There are 2 best solutions below

0
Silvio Mayolo On BEST ANSWER

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.

0
Ted Lyngmo On

When using the FormattedInputfunction basic_istream& operator>>( int& value ), it will extract an int and will by default skip any preceding whitespaces. That's part of what the formatted input functions do.

why is cin.ignore(); necessary before using getline(cin, name);

std::getline is an UnformattedInputFunction which will not skip whitespaces.

Mixing formatted and unformatted input often leads to problems so either stick to one or the other or you'll have to manually deal with lingering characters after formatted input when you switch to unformatted input.