Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fflush(stdin)

Tags:

c

stdin

fflush

So a quick Google search for fflush(stdin) for clearing the input buffer reveals numerous websites warning against using it. And yet that's exactly how my CS professor taught the class to do it.

How bad is using fflush(stdin)? Should I really abstain from using it, even though my professor is using it and it seems to work flawlessly?

like image 650
wrongusername Avatar asked Jun 05 '10 04:06

wrongusername


1 Answers

Simple: this is undefined behavior, since fflush is meant to be called on an output stream. This is an excerpt from the C standard:

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 it's not a question of "how bad" this is. fflush(stdin) is simply not portable, so you should not use it if you want your code to be portable between compilers.

like image 137
Eli Bendersky Avatar answered Oct 06 '22 00:10

Eli Bendersky