views:

5765

answers:

6

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

A: 

The following should work:

cin.flush();

On some systems it's not available and then you can use:

cin.ignore(INT_MAX);
Gunnar Steinn
why manually write a loop when you can tell ignore the read INT_MAX chars until it reaches EOF (the default value of the second param).
Evan Teran
You are right :)
Gunnar Steinn
Gunnar, might be better to edit your post to reflect this, just in case.
Dana the Sane
+7  A: 

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(); after this too to reset the stream state.

Evan Teran
(Old I know.) Clear before, rather, so the stream is put into a good state where it can operate on its buffer.
GMan
+21  A: 

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')
Martin York
More importantly, the values might be different! (streamsize doesn't have to be int)
Roger Pate
A: 

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.

Shadow2531
+1  A: 

How about:

cin.ignore(cin.rdbuf()->in_avail());
A: 
int i;
  cout << "Please enter an integer value: ";

  // cin >> i; leaves '\n' among possible other junk in the buffer. 
  // '\n' also happens to be the default delim character for getline() below.
  cin >> i; 
  if (cin.fail()) 
  {
    cout << "\ncin failed - substituting: i=1;\n\n";
    i = 1;
  }
  cin.clear(); cin.ignore(INT_MAX,'\n'); 

  cout << "The value you entered is: " << i << " and its double is " << i*2 << ".\n\n";

  string myString;
  cout << "What's your full name? (spaces inclded) \n";
  getline (cin, myString);
  cout << "\nHello '" << myString << "'.\n\n\n";
Randy