First, not all iostream is buffered; buffering is handled by the attached
streambuf
. In the case of filebuf
(used by ifstream
and
ofstream
), input will read as much as possible, up to the size of the
buffer, and output will flush the buffer on overflow, when an
explicit flush or close occurs, or when the object is destructed (which
implicitly calls close).
The case of cout
is a bit special, since it is never destructed nor
closes. There is a guarantee from the system that flush
will be
called on it at least once after exit
is called (which is what happens
when you return from main
). This means that any output before
returning from main will be flushed; if you're using cout
in
destructors of static objects, you still need an explicit flush to be
sure.
It's also possible to tie
an output stream to an input stream; cout
is tied to cin
by default. In this case, any attempt to input from
the tied stream will flush the output.
The usual convention is to just use std::endl
instead of simply
outputting '\n'
; std::endl
outputs a '\n'
and then flushes the
stream. For streams where it is very important for all output to appear
promptly, there is a unitbuf
flag which can be set, which means that
the stream will be flushed at the end of each <<
operator.
(std::cerr
has this set by default.)
Finally, if you want to see the effect of buffering, put something like
sleep(10)
after your output. If it output appears immediately, it has been
flushed; if it doesn't it has been buffered, and the flush occured
implicitly after the sleep
.
std::cout
is buffered normally. (This is different fromstdout
in C, which is line buffered if it is connected to an interactive device, and fully buffered otherwise. C++ doesn't have the concept of line buffering; usingstd::endl
effectively simulates it.) – Jaret