|
||||
|
« 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 streamYou should never use fflush() to clear any input stream, including stdin. According to the C Standard:
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:
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 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.
|
GIDNetwork Sites
Archives
Recent GIDBlog Posts
Recent GIDForums Posts
Contact Us
|
« Things to Avoid in C/C++ -- gets() , Part 1 | Things to Avoid in C/C++ -- feof(), Part 3 » |