Search code examples
c++class-library

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!


Solution

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