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

2019-01-22 12:42发布

问题:

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?

回答1:

Just insert std::flush:

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

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



回答2:

In addition to Joseph Mansfield answer, std::endl does the flush too (besides a new line).

Inserts a endline character into the output sequence os and flushes it as if by calling os.put(os.widen('\n')) followed by os.flush().



标签: c++ cout flush