How do I flush the cin buffer?


Question

How do I clear the cin buffer in C++?

1
103
11/2/2008 8:06:25 PM

Accepted Answer

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.

94
1/15/2016 10:30:37 PM

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')

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon