[英]How to disable cout output in the runtime?
我經常在代碼中的許多不同地方使用cout
進行調試,然后我感到沮喪並手動注釋所有這些。
有沒有辦法在運行時抑制 cout 輸出?
更重要的是,假設我想抑制所有cout
輸出,但我仍然希望在終端中看到 1 個特定輸出(假設程序的最終輸出)。
是否可以使用“其他方式”打印到終端來顯示程序輸出,然后在抑制 cout 時仍然看到使用這種“其他方式”打印的內容?
當然,你可以(這里的例子):
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
狀態將使其靜默丟棄任何輸出,直到清除fail
位。
不要將cout
用於調試目的,而是定義一個調用它的不同對象(或函數或宏),然后您可以在一個地方禁用該函數或宏。
要抑制輸出,您可以斷開底層緩沖區與 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;
}
您可以使用cerr
- 用於調試目的的錯誤的標准輸出流。
此外,還有clog
- 用於記錄的標准輸出流。
通常,它們的行為都像cout
。
例子:
cerr << 74 << endl;
看來您打印了調試消息。 您可以在 Visual C++/MFC 中使用TRACE ,或者您可能只想創建一個Debug()
函數來處理它。 只有在設置了不同的標志時,您才能實現它以打開。 例如,許多程序使用名為verbose
或-v
的命令行參數來控制其日志和調試消息的行為。
如果您包含涉及cout
文件,您可能希望在開始時(在 main 之外)編寫代碼,可以這樣完成:
struct Clearer {
Clearer() { std::cout.setstate(std::ios::failbit); }
} output_clearer;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.