-
fflush(stdin)
Before someone points me to the FAQ just for posting a thread with that kind of a subject, let me say that I already read it. That's why I have a question.
The FAQ says it's bad. CPPReference says it's okay. Eskimo.com says it's bad. CPlusPlus.com says it's okay.
It seems like every other source tells a different story. Which is it? And why is there so much conflicting information?
-
just don't use it in C programming, it's undefined behaviour
-
Hello,
Some people believe that fflush(stdin); may be used to clear the input stream, stdin. Like seen here.
Though, in reality, it is undefined behavior because the standard only provides words to make sense out of fflush() with output streams, not input streams. The reason this is so is because the stdio buffer and the operating system buffer are usually two different buffers.
Here is a brief explanation of fflush(): If the given stream has been opened for writing operations the output buffer is phisically written to the file. When a file is closed all the buffers associated with it are automatically flushed.
- Stack Overflow
-
The problem comes because on a windows system the operating system will allow you to flush an input stream.
But lets think about this logically for a minute:
flushing an output stream is fairly simple, you have a buffer to store the information to write and by flushing you cause all the information to go to the assocated stream. It really doesn't matter how big or small the buffer is.
Now lets think about an input stream. It too is buffered. So when you flush it, it should empty the buffer, but where should the data go? With the output it has an assocated file to send the information to, not so with the input stream. The size of the buffer matters in this case, what if the buffer was large enough to handle your entire file? By flushing it you've now lost all that information.
Theres no standard method for flushing an input stream because there is no one method that will work in all cases.
-
> It seems like every other source tells a different story. Which is it?
The only source worth a damn is the standard itself.
Those sites which say it's OK have a rather unpleasant M$ after-taste.
You can tell that the examples in the CPPReference.com site were written by a VC++ programmer who didn't know how to compile C.
-
in TCPL Appendix A, Kernighan and Ritchie said:
Code:
int fflush(FILE *stream)
On an output stream, fflush causes any buffered but unwritten
data to be written; on an input stream, the effect is undefined.
It returns EOF for a write error, and zero otherwise.
fflush(NULL) flushes all output streams.