57

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?

user1810087
  • 5,146
  • 1
  • 41
  • 76
synaptik
  • 8,971
  • 16
  • 71
  • 98
  • 6
    I hear `std::endl` is pretty popular for this kinda thing... –  Feb 25 '14 at 21:37
  • 3
    @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. – leemes Feb 25 '14 at 21:43
  • @leemes 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. –  Feb 25 '14 at 21:48
  • @synaptik 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. – Abhishek Mane Jun 15 '21 at 07:11

2 Answers2

91

Just insert std::flush:

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

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

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
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().

user1810087
  • 5,146
  • 1
  • 41
  • 76