C++ clog 物件
定義和用法
clog
物件用於記錄有關程式狀態的日誌訊息。它的行為與 cout
完全相同,但它可以被重定向到不同的目的地,例如日誌檔案。clog
和 cerr
總是寫入到同一個目的地。
有關更詳細的用法,請參閱 <iostream> cout 物件。
雖然 clog
和 cerr
寫入到相同的目的地,但 clog
是帶緩衝區的,而 cerr
不是。帶緩衝區的輸出會臨時將輸出儲存在變數中,直到滿足特定條件時才寫入目的地。帶緩衝區的輸出效率更高,因為它們對檔案的寫操作更少。如果訊息很重要,請改用 cerr
,否則如果程式崩潰,它們可能會丟失。
注意: clog
物件在 <iostream>
標頭檔案中定義。
更多示例
示例
將 clog
重定向到檔案而不是控制檯
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int myNum = 12;
// Set "info.log" as the output file for the log messages
ofstream log("info.log");
clog.rdbuf(log.rdbuf());
// Write to the log file
clog << "The number " << myNum << " was given\n";
// Close the file
log.close();
return 0;
}