How do I clear the cin buffer in C++?
A:
The following should work:
cin.flush();
On some systems it's not available and then you can use:
cin.ignore(INT_MAX);
Gunnar Steinn
2008-11-02 17:34:44
why manually write a loop when you can tell ignore the read INT_MAX chars until it reaches EOF (the default value of the second param).
Evan Teran
2008-11-02 17:39:13
You are right :)
Gunnar Steinn
2008-11-02 17:50:20
Gunnar, might be better to edit your post to reflect this, just in case.
Dana the Sane
2008-11-02 20:08:40
+7
A:
possibly:
std::cin.ignore(INT_MAX);
this would read in and ignore everything until EOF. (you can also supply a second argument which is the character to read until (ex: '\n' to ignore a single line).
Also: You probably want to do a: std::cin.clear(); after this too to reset the stream state.
Evan Teran
2008-11-02 17:37:55
(Old I know.) Clear before, rather, so the stream is put into a good state where it can operate on its buffer.
GMan
2010-10-03 10:33:39
+21
A:
I would prefer the C++ size constraints over the C versions:
// Ignore to the end of file
cin.ignore(std::numeric_limits<std::streamsize>::max())
// Ignore to the end of line
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
Martin York
2008-11-02 18:34:19
More importantly, the values might be different! (streamsize doesn't have to be int)
Roger Pate
2009-11-16 20:35:52
A:
I prefer:
cin.clear();
fflush(stdin);
There's an example where cin.ignore just doesn't cut it, but I can't think of it at the moment.
Shadow2531
2008-11-02 18:55:44
A:
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";
Randy
2009-10-09 09:26:06