Empty the input buffer

How can I empty the input buffer? There is a function to do it?
std::cin.ignore
If I understood you correctly, then... there's no one single no-argument function to do it, but there is a way to do it without loops in your code.
#include <limits>

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

std::cin.ignore deletes (argument 1) characters or until (argument 2) is found, which is also discarded.
http://cplusplus.com/reference/iostream/istream/ignore/

Have fun! :)

-Albatross

EDIT: :P
Last edited on
Thank you.
Can you give me an example of code?
I seen the reference, but it's a bit complex.
Here's an example I pulled from the reference with a few comments thrown in:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// istream ignore
#include <iostream>
#include <limits>
using namespace std;

int main () {
  char first, last;

  cout << "Enter your first and last names: ";

  first=cin.get(); //Gets one character from the stream.
  cin.ignore(256,' '); //Ignores up to 256 characters, stopping when 256 characters have been found or after a space has been found.

  last=cin.get(); //Gets another character from the stream.

  cout << "Your initials are " << first << last;

  cin.ignore( numeric_limits <streamsize> ::max(), '\n' ); //Pause the console to that you can see what the output is.
  //std::numeric_limits <std::streamsize> ::max() is the largest number of characaters that cin can hold.
  return 0;
}


-Albatross
Last edited on
I'm sorry but I don't understand all your code.
cin.ignore( numeric_limits <streamsize> ::max(), '\n' );
You have write in the comment that this functione pause the console to allow me to see the output, and I've understand this. But how?
What does it mean <streamsize>? And why you use ignore() to pause the console?. I haven't never seen this way to write code.

Everything else is ok :)
Thank you very much!!
Topic archived. No new replies allowed.