Where is unread cin input stored?

Viewed 67

If I enter a string "Hello World" using cin then where will "World" be stored? How can I ignore that string ("World")?

If the string ("World") is stored in the buffer then I can't remove that using std::endl.

1 Answers

The "World" is stored in the buffer. Ignore it with cin.ignore(5); (the arguments depend on the text that you want to ignore, e. g. to ignore the next line in the buffer use cin.ignore(numeric_limits::max(), ā€˜\n’)).

Example 1 (Not using cin.ignore())

Program:

#include <iostream>
using std::cin;
using std::cout;
using std::string;

int main()
{
    string str1;
    cin >> str1;
    cout << "str1 is " << str1 << "\n";
    string str2;
    cin >> str2;
    cout << "str2 is " << str2 << "\n";
}

Input: Hello world

Output: "str1 is Hello str2 is world"

(As we can see "world" stayed in the buffer and str2 took the value without asking as again for std::cin).

Example 2 (Using cin.ignore())

Program:

#include <iostream>
using std::cin;
using std::cout;
using std::string;

int main()
{
    string str1;
    cin >> str1;
    cout << "str1 is " << str1 << "\n";
    cin.ignore(5); //Just added this line!
    string str2;
    cin >> str2;
    cout << "str2 is " << str2 << "\n";
}

Input: Hello world

Output: "str1 is Hello"

(As we can see now "world" has been ignored and it stays asking us for input in the second std::cin).

Related