以编程方式忽略 Cout

发布于 2024-12-09 07:09:50 字数 344 浏览 0 评论 0原文

有谁知道是否有一个技巧可以切换所有 cout << 函数以不打印出可见输出?我正在尝试将我和其他人编写的一些代码组合在一起以制作一个演示。我不想将输出重定向到文件,并且想要一个在 Windows 和 Linux 之间具有一定兼容性的解决方案。

在我的场景中,我有很多行代码,其中有各种 #defines 控制某些方法何时产生调试输出。我想这样称呼:

cout.off();
driverForAffectA();
driverForAffectB();
cout.on();
printSpecializedDebug();
exit(0);

Does anybody know if there is a trick to toggle all the cout << functions to not print out visible output? I am trying to hack together some code written by me and some other people to put together a demo. I would rather not redirect the output to a file and would like a solution that had some measure of compatibility between Windows and Linux.

In my scenario I have many many lines of code with with various #defines controlling when certain methods produce debug output. I want to call something like:

cout.off();
driverForAffectA();
driverForAffectB();
cout.on();
printSpecializedDebug();
exit(0);

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

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

发布评论

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

评论(2

吲‖鸣 2024-12-16 07:09:50

您可以更改 cout 的流缓冲区。

streambuf *old = cout.rdbuf();
cout.rdbuf(0);
cout << "Hidden text!\n";
cout.rdbuf(old);
cout << "Visible text!\n";

编辑:

感谢 John Flatness 的评论,您可以稍微缩短代码:

streambuf *old = cout.rdbuf(0);
cout << "Hidden text!\n";
cout.rdbuf(old);
cout << "Visible text!\n";

You can change cout's stream buffer.

streambuf *old = cout.rdbuf();
cout.rdbuf(0);
cout << "Hidden text!\n";
cout.rdbuf(old);
cout << "Visible text!\n";

Edit:

Thanks to John Flatness' comment you can shorten the code a bit:

streambuf *old = cout.rdbuf(0);
cout << "Hidden text!\n";
cout.rdbuf(old);
cout << "Visible text!\n";
谜泪 2024-12-16 07:09:50

为什么您不想重定向输出?如果是因为您希望保留其他输出,那么您可能会不走运。

如果只是为了让您不必在演示中的终端上输入复杂的 shell 表达式,我建议您制作一个启动脚本并在内部进行重定向。

或者将 stdout 重新打开到 main 顶部附近的 /dev/null

Why precisely do you not want to redirect the output? If it is because there is other output you wish to keep, you may be out of luck.

If it is just so you don't have to type a complex shell expression on a terminal in a demo, I suggest making a start script and doing the redirect inside.

That, or reopen stdout to /dev/null somewhere near the top of main.

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