GIDNetwork > Things to Avoid in C/C++ -- fflush(stdin), Part 2
Register
« Things to Avoid in C/C++ -- gets() , Part 1 Things to Avoid in C/C++ -- feof(), Part 3 »

Things to Avoid in C/C++ -- fflush(stdin), Part 2

by: WaltP - Sep 18, 2005

fflush() to clear the input stream

You should never use fflush() to clear any input stream, including stdin. According to the C Standard:

int fflush(FILE* stream);

Flushes stream stream and returns zero on success or EOF on error.

Effect undefined for input stream. fflush(NULL) flushes all output streams.

http://www.infosys.utas.edu.au/info/documentation/C/CStdLib.html#fflush

This means compilers do not have to define flushing of input streams. Now some have in fact defined this feature. This should still not be used. The reason:

You've been programming for a couple years now and are in the habit of flushing stdin because you always use scanf() (another function you should avoid*). You get a new job that has a compiler without this particular enhancement. Your programs no longer work. You will spend days trying to figure out what's wrong because you 'know' fflush() can't be the problem -- you've used it for years.

So you should avoid this operation from now on.

Here is a real-world example of the trouble caused by MS-C because they decided to enhance the standard: http://mail.python.org/pipermail/python-dev/2003-September/037939.html
Notice the difficulty in writing to the two different handlings of fflush()?

So what do you do if you can't use fflush()? Well, my first recommendation is not to use functions like scanf()* that love leaving junk in the input buffer. Find other ways to read your input and don't rely on functions that have unexpected anomalies or seemingly inconsistent results. Ouside of that, start checking returns from all your I/O functions (including scanf()) and start studying what functions actually do when input is not exactly as expected.

Your best bet, and I know this is beyond beginners so it's something to look forward to, you need to read a character buffer and parse the input yourself. There's only so much intelligence a canned C/C++ function can have. Until you can do this, you won't easily be able to create bulletproof input. Sorry.

*scanf() -- why it should be avoided is food for another thread.

Would you like to comment? This story has been viewed 158,937 times.
« Things to Avoid in C/C++ -- gets() , Part 1 Things to Avoid in C/C++ -- feof(), Part 3 »

__top__

Copyright © GIDNetwork™ 2001 - 2017

Another website by J de Silva

Page generated in : 0.02397 sec.