c++ force std::cout flush (print to screen)

synaptik picture synaptik · Feb 25, 2014 · Viewed 35.4k times · Source

I have code such as the following:

std::cout << "Beginning computations..."; // output 1
computations();
std::cout << " done!\n";                  // output 2

The problem, however, is that often output #1 and output #2 appear (virtually) simultaneously. That is, often output #1 does not get printed to the screen until after computations() returns. Since the entire purpose of output #1 is to indicate that something is going on in the background (and thus to encourage patience from the user), this problem is not good.

Is there any way to force the std::cout buffer to get printed before the computations() call? Alternatively, is there some other way (using something other than std::cout) to print to standard out that would fix this problem?

Answer

Joseph Mansfield picture Joseph Mansfield · Feb 25, 2014

Just insert std::flush:

std::cout << "Beginning computations..." << std::flush;

Also note that inserting std::endl will also flush after writing a newline.