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?
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.
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. A unit-buffered stream is a stream that has ios::unitbuf set.
std::flushFlushes the output sequence os as if by calling os. flush(). This is an output-only I/O manipulator, it may be called with an expression such as out << std::flush for any out of type std::basic_ostream.
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.
Just insert std::flush
:
std::cout << "Beginning computations..." << std::flush;
Also note that inserting std::endl
will also flush after writing a newline.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With