How do I clear the cin buffer in C++?
The following should work:
cin.flush();
On some systems it's not available and then you can use:
cin.ignore(INT_MAX);
How about:
cin.ignore(cin.rdbuf()->in_avail());
cin.clear();
fflush(stdin);
This was the only thing that worked for me when reading from console. In every other case it would either read indefinitely due to lack of \n, or something would remain in the buffer.
EDIT: I found out that the previous solution made things worse. THIS one however, works:
cin.getline(temp, STRLEN);
if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
int i;
cout << "Please enter an integer value: ";
// cin >> i; leaves '\n' among possible other junk in the buffer.
// '\n' also happens to be the default delim character for getline() below.
cin >> i;
if (cin.fail())
{
cout << "\ncin failed - substituting: i=1;\n\n";
i = 1;
}
cin.clear(); cin.ignore(INT_MAX,'\n');
cout << "The value you entered is: " << i << " and its double is " << i*2 << ".\n\n";
string myString;
cout << "What's your full name? (spaces inclded) \n";
getline (cin, myString);
cout << "\nHello '" << myString << "'.\n\n\n";
Another possible (manual) solution is
cin.clear();
while (cin.get() != '\n')
{
continue;
}
I cannot use fflush or cin.flush() with CLion so this came handy.
Easiest way:
cin.seekg(0,ios::end);
cin.clear();
It just positions the cin pointer at the end of the stdin stream and cin.clear() clears all error flags such as the EOF flag.