我正在使用正在向cout或打印警告消息的库cerr.我不希望此警告消息到达我的程序的输出.如何捕获此输出并将其输入/dev/null或类似?
MWE:
#include <iostream>
void foo()
{
std::cout << "Boring message. " << std::endl;
};
int main()
{
foo();
std::cout << "Interesting message." << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出应该是:
Interesting message.
Run Code Online (Sandbox Code Playgroud)
我main该如何修改以获得所需的输出?(foo不得更改.)
我尝试使用freopen()并fclose(stdout)按照此问题中的建议如何将stdout重定向到Windows应用程序中的某些可见显示?.结果是没有打印任何内容.
wre*_*r23 19
我可以建议一个黑客?在使用库函数之前,在相关流上设置错误/失败位.
#include <iostream>
void foo()
{
std::cout << "Boring message. " << std::endl;
}
int main()
{
std::cout.setstate(std::ios::failbit) ;
foo();
std::cout.clear() ;
std::cout << "Interesting message." << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Seb*_*ach 18
如果您确定该东西不会重定向输出(例如/dev/tty/,再次标准输出)(我不认为),您可以在调用它们之前重定向.
#include <iostream>
#include <sstream>
void foobar() { std::cout << "foobar!\nfrob!!"; }
int main () {
using namespace std;
streambuf *old = cout.rdbuf(); // <-- save
stringstream ss;
cout.rdbuf (ss.rdbuf()); // <-- redirect
foobar(); // <-- call
cout.rdbuf (old); // <-- restore
// test
cout << "[[" << ss.str() << "]]" << endl;
}
Run Code Online (Sandbox Code Playgroud)
使用ios :: rdbuf:
#include <iostream>
void foo()
{
std::cout << "Boring message. " << std::endl;
}
int main()
{
ofstream file("/dev/null");
//save cout stream buffer
streambuf* strm_buffer = cout.rdbuf();
// redirect cout to /dev/null
cout.rdbuf(file.rdbuf());
foo();
// restore cout stream buffer
cout.rdbuf (strm_buffer);
std::cout << "Interesting message." << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13662 次 |
| 最近记录: |