FAQ > Flush the input buffer


Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > How do I... (Level 2) > Flush the input buffer

This item was added on: 2003/02/10

On occasions you may need to clear unwanted data in an input stream, most commonly keyboard input. This may be after a call to a read function that failed to input all available data, or it may be to ensure that the user doesn't try the "type ahead" approach when using your application.

As far as standard C and C++ go, there is no guaranteed method to clear an input stream. You can write code that will do a reasonably good job, but it probably won't work in all instances your require it to. Why not? Because in standard C/C++ input streams are buffered. This means that when you hit a key on the keyboard, it isn't sent directly to your program. Instead it is buffered by the operating system until such time that it is given to your program. The most common event for triggering this input is the pressing of the [Enter] key.

If you are sure that unwanted data is in the input stream, you can use some of the following code snippets to remove them. However, if you call these when there is no data in the input stream, the program will wait until there is, which gives you undesirable results.


/*
 *  This C implementation will clear the input buffer.
 *  The chances are that the buffer will already be empty,
 *  so the program will wait until you press [Enter].
 */

#include <stdio.h> 

int main(void)
{
  int   ch;
  char  buf[BUFSIZ];
  
  puts("Flushing input");
  
  while ((ch = getchar()) != '\n' && ch != EOF);
  
  printf ("Enter some text: ");
  
  if (fgets(buf, sizeof(buf), stdin))
  {
    printf ("You entered: %s", buf);
  }
  
  return 0;
}

/*
 * Program output:
 *
 Flushing input
 blah blah blah blah
 Enter some text: hello there
 You entered: hello there
 *
 */

And a C++ version:


#include <iostream> 
#include <cstdio> 

using std::cin;
using std::cout;
using std::endl;

int main(void)
{
  int ch;
  char buf[BUFSIZ];
    
  cout <<"Flushing input" <<endl;
  
  while ((ch = cin.get()) != '\n' && ch != EOF);
  
  cout <<"Enter some text: ";
  cout.flush();
  
  if (cin.getline(buf, sizeof(buf)))
  {
    cout <<"You entered: " <<buf <<endl;
  }

  return 0;
}

/*
 * Program output:
 *
 Flushing input
 blah blah blah blah
 Enter some text: hello there
 You entered: hello there
 *
 */


But what about fflush(stdin);

Some people suggest that you use fflush(stdin) to clear unwanted data from an input buffer. This is incorrect, read this FAQ entry to find out why.

Script provided by SmartCGIs