+ 8

How to flush the cout output stream buffer in C++

Does using endl in the stream guarantee a flush? Do you have to use cout << ... << flush? Is the behaviour the same on Linux and Windows?

14th Sep 2018, 6:04 AM
Sonic
Sonic - avatar
2 Antworten
+ 5
Asiya Rehman thanks, I was more after flushing the cout output stream buffer not clearing the screen. Ipang is correct.
15th Sep 2018, 1:52 PM
Sonic
Sonic - avatar
+ 4
1. Yes, inserting std::endl flushes the output stream, difference is, before it flushes, a new line character is inserted. std::flush itself doesn't automatically inserts new line character. 2. Not really, flush only if you want the stream buffer content to be sent to the output device instantly (realtime output). Otherwise leave it for std::cout to flush itself when its buffer is full, if you use std::endl or std::flush inside a loop you make a big overhead from forcing the stream to flush while there is still room in the buffer. 3. I cannot say for sure, as I don't have a solid proof regarding stream behaviour amongst different systems. More details of what std::flush be, and how it works under the hood: https://stackoverflow.com/questions/14105650/how-does-stdflush-work Hth, cmiiw
14th Sep 2018, 8:02 AM
Ipang