Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unbuffered output with cout

Tags:

c++

cout

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);
}
like image 731
Charles Salvia Avatar asked Sep 04 '09 03:09

Charles Salvia


People also ask

Is cout buffered?

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 buffered and unbuffered in C++?

To combat this C++ streams have a buffer (a bank of memory) that contains everything to write to the file or output, when it is full then it flushed to the file. The inverse is true for input, it fetches more when it the buffer is depleted. Would be 4 writes to a file which is inefficient.


1 Answers

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;
like image 162
mrduclaw Avatar answered Sep 18 '22 15:09

mrduclaw