views:

591

answers:

3

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!

+5  A: 

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.)

Chris Jester-Young
+3  A: 

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.

Greg Rogers
A: 

Usually, when it's important to see the output immediately, we're talking about complex highly-reliable financial routine that must log a transaction all the way to hard drive before actually sending it to counterparty. Or, (much more common case) we want to see debug messages even when the program is crashing.

Since you're studying, I'll assume you're dealing with the second case. In that case, my advice would be to use stderr rather than stdout. It is unbuffered by default, and you can redirect it separately from stdout, putting your output in one place and your logging in another.

Arkadiy