重置 ostream,C++

发布于 2024-10-04 17:55:10 字数 1039 浏览 0 评论 0原文

我有 2 个不同的 ostream,其中之一是 cerr,使用相同的流缓冲区,我有一些库可能以某种方式修改了 cerr,(标志?格式修饰符?)。

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

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

打印:

This
is
a
test
This is a teststream test

调试 mystreambuffer 我注意到 cerr 在每个 << 操作中调用 mystreambuffer->sync() 而 teststream 不调用根本就是这样。
如果我是正确的 cerr 只是一个标准的 ostream,那么,为什么我会看到刷新时间的这种差异?如何将 cerr 重置回正常的刷新操作?

编辑:我看到你们在评论unitbuf并且它是cerr中的默认值,但是如果它是默认的,它不是也会在这里一步步写吗?

#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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

为你拒绝所有暧昧 2024-10-11 17:55:10

尝试 std::cerr.unsetf( std::ios_base::unitbuf );。默认情况下,cerr 会启用该标志。

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

撑一把青伞 2024-10-11 17:55:10

ios::unitbuf 标志是 cerr 设置为默认值的原因。

您需要使用 nounitbuf 操纵器来修复它。一些较旧的库可能没有它,如果有,则使用 unsetf。

编辑:
unitbuf 的默认设置取决于实现:)

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 :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文