20

How can you get unbuffered output from cout, so that it instantly writes to the console without the need to flush (similar to cerr)?

I thought it could be done through rdbuf()->pubsetbuf, but this doesn't seem to work. The following code snippet below is supposed to immediately output to the console, and then wait a few seconds. But instead, it just waits, and only outputs when the program exits and the buffer is flushed.

#include <iostream>

int main()
{
        std::cout.rdbuf()->pubsetbuf(0, 0);
        std::cout << "A";
        sleep(5);
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Charles Salvia
  • 52,325
  • 13
  • 128
  • 140

1 Answers1

45

You can set the std::ios_base::unitbuf flag to flush output after each output operation either by calling std::ios_base::setf:

std::cout.setf(std::ios::unitbuf);

or using the std::unitbuf manipulator:

std::cout << std::unitbuf;
outis
  • 75,655
  • 22
  • 151
  • 221
mrduclaw
  • 3,965
  • 4
  • 36
  • 37
  • This solution indeed worked for me, thanks! A note to others: the buffering appears to happen when using cout or printf and happens even if a newline is used at the end of the line. – Moot May 05 '17 at 06:13