#include <iostream>
using std::cout;
using std::endl;
using std::cerr;
#include <cstdio>
int main( )
{
char pbuffer[BUFSIZ];
setbuf(stdout, pbuffer);
cout << "hello cout" ;
sleep(5);
cerr << "hello cerr";
sleep(5);
cout << "\nAll done " << endl;
sleep(5);
return 0;
}
after I compile and run the program above, it's output is :
hello couthello cerr
All done
but I think it should be:
hello cerrhello cout
All done
I want to know, why cerr
flushes the buffer of cout
?
This is by design.
Both cin
and cerr
are tied to cout
, and calls cout.flush() before any of their own operations.
The idea is probably that input and output should occur in a proper order.
First, a stream is allowed to flush whenever it feels like it. I possible that some implementations of iostream do change buffering policies when outputting to an interactive device. Unless you intentionally flush between outputs on the two streams, the order they appear is more or less unspecified; all you can count on is that a single <<
to cerr
will not have characters from cout
inserted into it. In your case, the implementation is synchronizing cout
and cerr
in some way. (You might want to see what happens if you redirect their output to different files. Or to the same non-interactive file—C++ makes no distinction between interactive devices and others, but C does, and I expect that most C++ implementations follow C in this respect.)
FWIW, the two guarantees concerning order are:
cout
is tied to cin
, so any attempt to read on cin
will flush cout
, andcerr
has unitbuf
set, so it will be flushed at the end of every <<
operator.The idea behind the latter is, I think, to obtain something similar to C's line buffering, which C++ doesn't support directly—although if you use std::endl
, you get the same effect as line buffering.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With