I have some C++ code that uses cout
statements for debug purposes and for some reason I can't get all the data to print unless I do a std::cout.flush();
at the end.
I don't quite understand why this flush operation is needed.
Anyone have any insight?
The fflush function in C is used to immediately flush out the contents of an output stream. This is particularly useful in displaying output, as the operating system may initially put the output data in a temporary buffer before writing it to an output stream or file like stdout .
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).
To clarify the title of the question: printf(..) does not do any flushing itself, it's the buffering of stdout that may flush when seeing a newline (if it's line-buffered).
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.
Are you using std::endl
to terminate your lines. This should be the usual practice, until performance issues require otherwise, but for some reason, I see a lot of code which uses '\n'
instead.
Otherwise, you can always do:
std::cout.setf( std::ios_base::unitbuf );
as one of the first things in main
. This will cause a flush at the end of every <<
, which is more than you need, but for diagnostic output to the console, is probably quite acceptable.
To add to the other answers: your debugging statements should instead go to cerr
, because:
cerr
by default is unbuffered, which means that, after each output operation, it will automatically flush itself, and in general this is desirable for errors and debug output.(source: C++ standard, §27.3.1 ¶4-5, §27.4.2.1.2 table 83)
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