문제

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 " << " test\n";
    std::cout << "This " << " is " << " a cout " << " test\n";
}
Cobain /tmp$ ./test 
This  is  a cerr  test
This  is  a cout  test
도움이 되었습니까?

해결책

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

다른 팁

ios::unitbuf flag is the reason for that which is set to default for cerr.

You need to use the nounitbuf manipulator in order to fix it. Some older libraries may not have it, if so then use unsetf.

Edit: Default setting for unitbuf is implementation-dependent :)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top