开发者

stdout and need to flush it C++

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?


To add to the other answers: your debugging statements should instead go to cerr, because:

  • it writes to the standard error, which means that, running the application, you can easily separate the "normal" program output from the errors/debug information via redirection;
  • most importantly, 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)


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.


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.


"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


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.


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.


In C++ you can use endl formatter with cout operator rather then flush.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜