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

2

64

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?

Gantt answered 25/2, 2014 at 21:35 Comment(5)
I hear std::endl is pretty popular for this kinda thing...Least
@ebyrob But this will end the line, and if he wants to continue printing on the same line after the computation, he needs to manually flush.Ruthy
@Ruthy that's very true. In that case he can either use fprintf(), std::flush (as below), or modify his version of cout to automatically flush at the end of each line of code... I had a SO thread for that last one but seem to have lost it.Least
@Gantt what you facing I am not facing. it's working fine. I just made computation function with one cout line. but it is printing that "Beginning computations..." before calling the function. but I need to find at which particular case buffer will not free.Magenmagena
Am using gcc compiler. Added "-static" flag and it worked. See this so ansSuburbanize
L
103

Just insert std::flush:

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

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

Lidda answered 25/2, 2014 at 21:36 Comment(3)
@user1810087 Sorry, I edited it in, but pretty quickly. I think it was before you answered.Lidda
I enjoyed the comments :DHalide
@JosephMansfield but in my case it is not happening means there is no need to use of std::flush. can you give a case where buffer is not full so cout is not printing.Magenmagena
F
9

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().

Firmament answered 25/2, 2014 at 21:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.