How to clear the input buffer with TTY set to raw mode using std::cin?

479 views Asked by At

So I've used the termios library to put the terminal into raw mode, which allows me to do this:

int getch() {
  int ch;
  do {
    ch = cin.get();
  } while(cin.eof());
  return ch;
}

This waits for a single character to be ready in the input buffer and returns it.

But if I try to do this:

void clear_input_buffer() {
  char ch;
  while(!cin.fail()) {
    cin.get(ch);
  }
}

It goes into an endless loop.

What would be the appropriate way to clear the input buffer? I've tried this:

cin.clear();
cin.ignore(INT_MAX);

But it also hangs. I'd also like to do this using only iostreams or standard posix functions.

1

There are 1 answers

0
David G On BEST ANSWER

Just do the usual:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');