Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does cout flush?

I know endl or calling flush() will flush it. I also know that when you call cin after cout, it flushes too. And also when the program exit. Are there other situations that cout flushes?

I just wrote a simple loop, and I didn't flush it, but I can see it being printed to the screen. Why? Thanks!

for (int i =0; i<399999; i++) {

        cout<<i<<"\n";

}

Also the time for it to finish is same as withendl both about 7 seconds.

for (int i =0; i<399999; i++) {

        cout<<i<<endl;

}
like image 587
Arch1tect Avatar asked Mar 12 '14 07:03

Arch1tect


People also ask

Does cout flush automatically?

It is an implementation detail, one that invariably depends on whether output is redirected. If it is not then flushing is automatic for the obvious reason, you expect to immediately see whatever you cout. Most CRTs have an isatty() helper function that is used to determine whether automatic flushing is required.

What is cout << flush?

The predefined streams cout and clog are flushed when input is requested from the predefined input stream (cin). The predefined stream cerr is flushed after each output operation. An output stream that is unit-buffered is flushed after each output operation.

What is cout << flush in C++?

In C++, we can explicitly be flushed to force the buffer to be written. Generally, the std::endl function works the same by inserting a new-line character and flushes the stream. stdout/cout is line-buffered that is the output doesn't get sent to the OS until you write a newline or explicitly flush the buffer.

What is flush () in C++?

C++ manipulator flush is used to synchronize the associated stream buffer with its controlled output sequence. For the stream buffer, objects that implement intermediate buffers, flush function is used to request all characters written to the controlled sequence.


1 Answers

There is no strict rule by the standard - only that endl WILL flush, but the implementation may flush at any time it "likes".

And of course, the sum of all digits in under 400K is 6 * 400K = 2.4MB, and that's very unlikely to fit in the buffer, and the loop is fast enough to run that you won't notice if it takes a while between each output. Try something like this:

 for(int i = 0; i < 100; i++)
 {
   cout<<i<<"\n";
   Sleep(1000);
 }

(If you are using a Unix based OS, use sleep(1) instead - or add a loop that takes some time, etc)

Edit: It should be noted that this is not guaranteed to show any difference. I know that on my Linux machine, if you don't have a flush in this particular type of scenario, it doesn't output anything - however, some systems may do "flush on \n" or something similar.

like image 136
Mats Petersson Avatar answered Sep 22 '22 20:09

Mats Petersson