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;
}