【问题标题】:How to disable cout output in the runtime?如何在运行时禁用 cout 输出?
【发布时间】:2015-07-22 23:31:38
【问题描述】:

我经常在代码中的许多不同位置使用cout 进行调试,然后我感到沮丧并手动注释所有这些。

有没有办法在运行时抑制 cout 输出?

更重要的是,假设我想抑制所有 cout 输出,但我仍然想在终端中看到 1 个特定输出(比如说程序的最终输出)。

是否可以使用“其他方式”打印到终端以显示程序输出,然后在抑制 cout 时仍然看到使用此“其他方式”打印的内容?

【问题讨论】:

    标签: c++ cout


    【解决方案1】:

    您可以使用cerr - 标准输出流,用于调试错误。

    此外,还有clog - 用于记录的标准输出流。

    通常,它们的行为都像cout

    例子:

    cerr << 74 << endl;
    

    详情:http://www.cplusplus.com/reference/iostream/cerr/

    http://www.cplusplus.com/reference/iostream/clog/

    【讨论】:

      【解决方案2】:

      不要将cout 用于调试目的,而是定义一个调用它的不同对象(或函数或宏),然后您可以在一个地方禁用该函数或宏。

      【讨论】:

        【解决方案3】:

        当然可以 (example here):

        int main() {
            std::cout << "First message" << std::endl;
        
            std::cout.setstate(std::ios_base::failbit);
            std::cout << "Second message" << std::endl;
        
            std::cout.clear();
            std::cout << "Last message" << std::endl;
        
            return 0;
        }
        

        输出:

        First message
        Last message
        

        这是因为将流置于fail 状态会使其静默丢弃任何输出,直到故障位被清除。

        【讨论】:

          【解决方案4】:

          您似乎打印了调试消息。您可以在 Visual C++/MFC 中使用TRACE,或者您可能只想创建一个处理它的Debug() 函数。您可以实现它以仅在设置了不同的标志时才打开。例如,许多程序使用名为 verbose-v 的命令行参数来控制其日志和调试消息的行为。

          【讨论】:

            【解决方案5】:

            要抑制输出,您可以断开底层缓冲区与 cout 的连接。

            #include <iostream>
            
            using namespace std;
            
            int main(){
            
                // get underlying buffer
                streambuf* orig_buf = cout.rdbuf();
            
                // set null
                cout.rdbuf(NULL);
            
                cout << "this will not be displayed." << endl;
            
                // restore buffer
                cout.rdbuf(orig_buf);
            
                cout << "this will be dispalyed." << endl;
            
                return 0;
            }
            

            【讨论】:

            • 它有运行时开销吗?
            【解决方案6】:

            如果您包含涉及cout 的文件,您可能希望在开头(main 之外)编写代码,可以这样完成:

            struct Clearer {
                Clearer() { std::cout.setstate(std::ios::failbit); }
            } output_clearer;
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-05-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2023-03-10
              相关资源
              最近更新 更多