im curious as to the point in flushing streams? why is it necessary to do this? i never find input being left inside a buffer and needing to get forced to my output display :/

Lucky you. Some people do, and they need a way to know for sure that the stream and its output sequence are synchronised.

A simple example of when this is useful is when you are mixing output to stdout and stderr. stderr is not buffered and stdout is so it may be the case that printing to stdout will show up at unexpected locations if it is not flushed.

[Edit]
For example, on my system, if I run this:

#include <iostream>

int main () {
    std::cerr << "Error stream 1 ";
    std::cerr << "Error stream 2 ";
    std::cout << "Basic stream 1 ";
    std::cerr << "Error stream 3 ";
    std::cerr << "Error stream 4 ";
    return 0;
}

I get the following output

Error stream 1 Error stream 2 Error stream 3 Error stream 4 Basic stream 1

But if I insert a flush statement

std::cerr << "Error stream 2 ";
    std::cout << "Basic stream 1 ";
    std::cout.flush ();
    std::cerr << "Error stream 3 ";

The output becomes

Error stream 1 Error stream 2 Basic stream 1 Error stream 3 Error stream 4

Edited 5 Years Ago by L7Sqr: n/a

I very often use the flush for displaying the simulation time without printing lines after lines. Say I run a numerical simulation in big loop, I would insert in it:

while (..) {
  //... all the simulation code
  //print the current simulation time over the last one printed (without a new line)
  std::cout << "\rCurrent time: " << std::setw(10) << sim_time;
  std::cout.flush(); //flush is required, otherwise, this would not work.
};

There are plenty of other situations where flushing a stream is useful (even more so when the stream is a file stream).

Thanks everyone, does anyone happen to have any usedull resources regarding flushing streams?

This article has been dead for over six months. Start a new discussion instead.