Why fflush(..)
doesn\'t work to c2
and c0
?
If I use the declaration c0 = 0
and c2 = 0
it works, but
On your system ubuntu 13.04 (Unix or Linux) calling fflush (stdin);
is undefined behavior!
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
To learn a trick to flush the input buffer correctly, you can use some of the following code snippets that actually read and discard unwanted chars from input buffer. You can use this as fflush before reading actual data. read this FAQ entry.
for C:
while ((ch = getchar()) != '\n' && ch != EOF);
for C++:
while ((ch = cin.get()) != '\n' && ch != EOF);
However, if you call these when there is no data in the input stream, the program will wait until there is, which gives you undesirable results.
Read: @Keith Thompson's answer: "Alternative to C library-function fflush(stdin)"
Edit:
There are platforms where fflush(stdin)
is fully defined (as a non-standard extension on that platform). The primary example is a well-known family of systems known collectively as Windows. Microsoft's specification:
Flushes a stream
The
int fflush(FILE *stream )
function flushes a stream. If the file associated with stream is open for output,fflush
writes to that file the contents of the buffer associated with the stream. If the stream is open forinput
,fflush
clears the contents of the buffer.fflush
negates the effect of any prior call to ungetc against stream. Also,fflush(NULL)
flushes all streams opened for output. The stream remains open after the call. fflush has no effect on an unbuffered stream.
fflush(stdin)
has undefined behavior.Use this henceforth to deal with the newline that remains in the stdin
buffer while using scanf()
,especially in cases when you need to read a character but the newline remaining in the buffer is automatically taken up as the character :
while((c = getchar()) != '\n' && c != EOF);
Here's what the cplusplusreference
says about fflush()
(You can verify the same from other sources as well,because too many veterans here on SO frown upon cplusplusreference
though they fall short of condemning it altogether)
......In some implementations, flushing a stream open for reading causes its input buffer to be cleared (but this is not portable expected behavior).....
http://www.cplusplus.com/reference/cstdio/fflush/