Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
586 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

Should do the trick.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...