Skip to content
Advertisement

Resetting an ostream, C++

I have 2 different ostreams, one of them cerr, using the same streambuffer, I have some libraries in that might have modified cerr somehow,(flags? format modifiers?).

cerr.rdbuf(&mystreambuffer);
ostream teststream(&mystreambuffer);

cerr << "This " << " is " << " a " << " test";
teststream << "This " << " is " << " a teststream " << " test";

prints:

This
is
a
test
This is a teststream test

Debugging mystreambuffer I’ve noticed that cerr calls mystreambuffer->sync() every << operation while teststream does not call it at all.
If I am correct cerr is just an standard ostream, then, why do I see this difference in flushing times? How can I reset cerr back to normal flushing operations?

EDIT: I see you guys are commenting about unitbuf and it being default in cerr, but if it was default, wouldn’t it write step by step here as well?

#include <iostream>
int main(){
    std::cerr << "This " << " is " << " a cerr " << " testn";
    std::cout << "This " << " is " << " a cout " << " testn";
}
Cobain /tmp$ ./test 
This  is  a cerr  test
This  is  a cout  test

Advertisement

Answer

Try std::cerr.unsetf( std::ios_base::unitbuf );. That flag is on for cerr by default.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement