使用字符串流将 stderr 重定向到 stdout
我有这样的代码
int main()
{
std::stringstream oss;
std::cerr.rdbuf( oss.rdbuf() );
std::cerr << "this goes to cerr";
std::cout << "[" << oss.str() << "]";
}
但是我得到的程序输出为
[this goes to cerr]Segmentation fault
程序段错误如何?
I have a code like this
int main()
{
std::stringstream oss;
std::cerr.rdbuf( oss.rdbuf() );
std::cerr << "this goes to cerr";
std::cout << "[" << oss.str() << "]";
}
But i get the output of the program as
[this goes to cerr]Segmentation fault
How does the program segfault?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为您在程序退出之前没有恢复 cerr 的缓冲区。这样做:
请参阅我的这个答案异常安全的解决方案。
This is because you do not restore the buffer of
cerr
before your program exits. Do it like this:See this answer of mine for a solution that is exception safe.
另一个答案正确地解决了您的问题的
此程序如何发生段错误
部分。然而,我觉得真正的问题Redirecting stderr to stdout using string stream..
值得一个更好的答案:您可以简化整个 shebang 并使其扩展并通过仅将 cerr 别名为cout:
如果您确实想明确:
您可以验证运行时是否在 stdout 上实际接收到文本
The other answer correctly address the
how does this program segfault
part of your question. However, I feel that the real questionRedirecting stderr to stdout using string stream..
deserves a better answer:You may simplify the whole shebang and make it scale and perform a infitely better better by just aliasing cerr to cout:
If you really want to be explicit:
You can verify that the text is actually received on stdout when run