Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does setbuf() affect cout?

Yet again, my teacher was unable to answer my question. I knew who may be able to...

So, I've never really learned C. In C++, I would, obviously, use a cout statement all of the time. In a recent assignment, my teacher told us to make sure to put

setbuf( stdout , NULL );

at the top of main() in order to get an unbuffered output, thus allowing us to see the output properly.

My question is this: will this statement affect a cout statement, or simply a printf() statement that I call?

Thanks in advance!

like image 628
Joe Fontana Avatar asked Apr 09 '26 05:04

Joe Fontana


2 Answers

By default, iostreams and stdio are synchronised. Reference.

This doesn't mean that manually adjusting the stdio buffering is a good idea, though! You may wish to utilise std::endl or std::flush (from <ostream>), which may help you. e.g.,

std::cout << "Hello, world!" << std::endl;

or

std::cout << "Hello, world!\n" << std::flush;

Both of these do the same thing. (std::endl = print endline, then flush.)

like image 148
Chris Jester-Young Avatar answered Apr 10 '26 20:04

Chris Jester-Young


By default, if stdout or cout is printing to a console, the output is line buffered. This means that every newline that is printed will flush the output. You can explicitly call flush() whenever you want to override the behavior just in case say, the output is going to be redirected to a file and you want to use tail -f and need certain outputs in realtime.

As Chris said, sync_with_stdio should tie the unbuffered stdout with an unbuffered cout (by default), but if all you are doing is using cout, instead of using setbuf on stdout, a better option is to use pubsetbuf on the pointer returned by rdbuf. ie:

// make cout unbuffered
std::cout.rdbuf()->pubsetbuf(0, 0);

Another function that may be interesting to look at is tie.

like image 27
Greg Rogers Avatar answered Apr 10 '26 20:04

Greg Rogers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!