How do I clear the cin buffer in C++?
I would prefer the C++ size constraints over the C versions:
// Ignore to the end of Stream
std::cin.ignore(std::numeric_limits<std::streamsize>::max())
// Ignore to the end of line
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
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(); before this too to reset the stream state.
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. It was a while ago when I needed to use it (with Mingw).
However, fflush(stdin) is undefined behavior according to the standard. fflush() is only meant for output streams. fflush(stdin) only seems to work as expected on Windows (with GCC and MS compilers at least) as an extension to the C standard.
So, if you use it, your code isn't going to be portable.
See Using fflush(stdin).
Also, see http://ubuntuforums.org/showpost.php?s=9129c7bd6e5c8fd67eb332126b59b54c&p=452568&postcount=1 for an alternative.
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.
The following should work:
cin.flush();
On some systems it's not available and then you can use:
cin.ignore(INT_MAX);
fflush(stdin) − It is used to clear the input buffer memory. It is recommended to use before writing scanf statement.
fflush(stdout) − It is used for clearing the output buffer memory. It is recommended to use before printf statement. The following should work:
cin.flush(); On some systems it's not available and then you can use:
cin.ignore(INT_MAX); Both Windows and Linux define the behaviour of fflush() on an input stream, and even define it the same way (miracle of miracles). The POSIX, C and C++ standards for fflush() do not define the behaviour, but none of them prevent a system from defining it. If you're coding for maximum portability, avoid fflush(stdin); if you're coding for platforms that define the behaviour, use it — but be aware that it is not portable portable code does not use fflush(stdin). Code that is tied to Microsoft's platform may use it and it may work as expected, but beware of the portability issues.