How do I flush the cin buffer?

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!


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.


cin.clear();
fflush(stdin);

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.

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

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

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