C++ cerr 对象
示例
使用 cerr 对象输出错误消息:
int x = 5;
int y = 0;
if(y == 0) {
cerr << "Division by zero: " << x << " / " << y << "
";
} 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;
// 将"error.log"设置为错误消息的输出文件
ofstream log("error.log");
cerr.rdbuf(log.rdbuf());
// 编写错误消息
if(y == 0) {
cerr << "Division by zero: " << x << " / " << y << "
";
} else {
cout << (x / y);
}
// 关闭文件
log.close();
return 0;
}

