C++ cerr 物件
示例
使用 cerr
物件輸出錯誤訊息
int x = 5;
int y = 0;
if(y == 0) {
cerr << "Division by zero: " << x << " / " << y << "\n";
} else {
cout << (x / y);
}
定義和用法
cerr
物件用於輸出錯誤訊息。它與 cout
的行為完全相同,但它可以被定向到不同的目的地,例如錯誤日誌檔案。cerr
和 clog
始終寫入同一目的地。
有關更詳細的用法,請參閱 <iostream> cout 物件。
與 cout
和 clog
不同,cerr
是非緩衝的。緩衝輸出會將輸出暫時儲存在一個變數中,直到滿足某些條件才寫入目的地。緩衝輸出效率更高,因為它減少了檔案寫入操作。cerr
不是緩衝的,這樣錯誤訊息就可以在程式崩潰前寫入檔案。
注意: cerr
物件在 <iostream>
標頭檔案中定義。
更多示例
示例
將 cerr
重定向到檔案而不是控制檯
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int x = 5;
int y = 0;
// Set "error.log" as the output file for the error messages
ofstream log("error.log");
cerr.rdbuf(log.rdbuf());
// Write an error message
if(y == 0) {
cerr << "Division by zero: " << x << " / " << y << "\n";
} else {
cout << (x / y);
}
// Close the file
log.close();
return 0;
}