Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stdout and need to flush it C++

Tags:

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?

like image 890
Dixon Steel Avatar asked Jun 02 '11 12:06

Dixon Steel


People also ask

Why do you need to flush the buffer C?

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 .

When should you flush 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).

Do you need to flush printf?

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).

How do you flush a C?

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.


2 Answers

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.

like image 34
James Kanze Avatar answered Nov 02 '22 16:11

James Kanze


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)

like image 64
Matteo Italia Avatar answered Nov 02 '22 18:11

Matteo Italia