Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

flush

cout

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?

like image 269
synaptik Avatar asked Feb 25 '14 21:02

synaptik


People also ask

How do you flush STD cout?

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 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. A unit-buffered stream is a stream that has ios::unitbuf set.

What is std :: flush C++?

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.

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.


1 Answers

Just insert std::flush:

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

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

like image 92
Joseph Mansfield Avatar answered Oct 19 '22 12:10

Joseph Mansfield