c++ – How do I flush the cin buffer?

c++ – How do I flush the cin buffer?

I would prefer the C++ size constraints over the C versions:

// Ignore to the end of file

// Ignore to the end of line
cin.ignore(std::numeric_limits<std::streamsize>::max(), n)



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.

c++ – How do I flush the cin buffer?


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.

I found out that the previous solution made things worse. THIS one however, works:

cin.getline(temp, STRLEN);
if (cin.fail()) {
    cin.ignore(numeric_limits<streamsize>::max(), n);

Leave a Reply

Your email address will not be published.