FAQ > Why fflush(stdin) is wrong


Match word(s).

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

FAQ > Explanations of... > Why fflush(stdin) is wrong

This item was added on: 2003/05/13

On occasions you may need to clear unwanted data in an input stream, most commonly keyboard input. One frequently suggested way of doing this is by using fflush(stdin). This is incorrect, and should be avoided, here is why. To learn how to flush the input buffer correctly, read this FAQ entry.

stdin is a standard FILE* variable that points to the input stream normally used for keyboard input. The fflush() function is deemed to flush buffers. Put the two together and you have a method for clearing the input stream easily, right? WRONG! This is a common misconception in C and C++ programming, an extract from the C standard will help explain:


int fflush(FILE *ostream);

ostream points to an output stream or an update stream in which the
most recent operation was not input, the fflush function causes any
unwritten data for that stream to be delivered to the host environment to
be written to the file; otherwise, the behavior is undefined.


So, if the file stream is for input use, as stdin is, the behaviour is undefined, therefore it is not acceptable to use fflush() for clearing keyboard input.

As usual, there are some exceptions, check your compiler's documentation to see if it has a (non-portable) method for flushing input.

Script provided by SmartCGIs