How do I clear the cin buffer in C++?
I have found two solutions to this.
The first, and simplest, is to use std::getline()
for example:
std::getline(std::cin, yourString);
... that will discard the input stream when it gets to a new-line. Read more about this function here.
Another option that directly discards the stream is this...
#include <limits>
// Possibly some other code here
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Good luck!
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.
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')
cin.get()
seems to flush it automatically oddly enough (probably not preferred though, since this is confusing and probably temperamental).
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.
#include <stdio_ext.h>
and then use function
__fpurge(stdin)