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.
while ((ch = getchar()) != '\n' && ch != EOF);
printf ("Enter some text: ");
if (fgets(buf, sizeof(buf), stdin))
printf ("You entered: %s", buf);
And a C++ version:
cout <<"Flushing input" <<endl;
while ((ch = cin.get()) != '\n' && ch != EOF);
cout <<"Enter some text: ";
if (cin.getline(buf, sizeof(buf)))
cout <<"You entered: " <<buf <<endl;
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.