stdout is line-buffered when connected to a terminal, but I remember reading somewhere that reading (at least from stdin) will automatically flush stdout. All C implementations that I have used have done this, but I can't find it in the standard now.
It does make sense that it works that way, otherwise code like this:
printf("Type some input: ");
fgets(line, sizeof line, stdin);
would need an extra fflush(stdout);
So is stdout guaranteed to be flushed here?
EDIT:
As several replies have said, there seems to be no guarantee in the standard that the output to stdout in my example will appear before the read from stdin, but on the other hand, this intent is stated in (my free draft copy of) the standard:
The input and output dynamics of interactive devices shall take place as specified in 7.19.3. The intent of these requirements is that unbuffered or line-buffered output appear as soon as possible, to ensure that prompting messages actually appear prior to a program waiting for input.
(ISO/IEC 9899:TC2 Committee Draft -- May 6, 2005, page 14).
So it seems that there is no guarantee, but it will probably work in most implementations anyway. (Famous last words...)
Clearing input buffer in C/C++The function fflush(stdin) is used to flush or clear the output buffer of the stream. When it is used after the scanf(), it flushes the input buffer also. It returns zero if successful, otherwise returns EOF and feof error indicator is set.
So, what it basically comes down to is pretty simple: when you read from stdin , if anything has been written to stdout , but not flushed yet, it'll be flushed automatically before the system waits for input from stdin (unless you've done something like redirecting one or both to a file).
Use the fflush Function to Flush stdout Output Stream in C As a result, there are buffers maintained by the C library for handling the input/output operations when using the stdio function calls. If the user needs to force writing to kernel buffers, it needs to flush the given stream provided by the fflush function.
stdout. flush() forces it to “flush” the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.
No, it does not.
To answer your question, you do need the extra fflush(stdout);
after your printf()
call to make sure the prompt appears before your program tries to read input. Reading from stdin
doesn't fflush(stdout);
for you.
No. You need to fflush(stdout); Many implementations will flush at every newline of they are sending output to a terminal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With