stdout and need to flush it C++

Dixon Steel picture Dixon Steel · Jun 2, 2011 · Viewed 38.3k times · Source

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?

Answer

Matteo Italia picture Matteo Italia · Jun 2, 2011

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)