Reputation: 1061
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?
Upvotes: 26
Views: 49445
Reputation: 3978
It is the right behavior. You probably use std::endl
that add \n
and flush the buffer. http://www.cplusplus.com/reference/ostream/endl/
You need to flush the stream, if you want to see the output.
Upvotes: 1
Reputation: 39807
Is the data that isn't automatically getting flushed lacking a \n
at the end? By default, standard out doesn't get delivered until a carriage return is seen.
Upvotes: 4
Reputation: 1638
In C++ you can use endl
formatter with cout
operator rather then flush
.
Upvotes: 1
Reputation: 1
The answer of std::endl
is only valid if you want a return.
Not sure how you would do this if you wanted to flush a command prompt out.
Upvotes: 0
Reputation: 126787
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)
Upvotes: 23
Reputation: 153919
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.
Upvotes: 13
Reputation: 5375
"When you send output to a stream, it does not necessarily get printed immediately. Rather, it may wait in a buffer until some unspecified event, e.g. buffer full enough, reading from input, or exit from program. The details may vary."
http://www.cs.hmc.edu/~geoff/classes/hmc.cs070.200109/notes/io.html
Upvotes: 1