C++ cerr object
Example
Use the cerr
object to output error messages:
int x = 5;
int y = 0;
if(y == 0) {
cerr << "Division by zero: " << x << " / " << y << "\n";
} else {
cout << (x / y);
}
Definition and Usage
The cerr
object is used to output error messages. It behaves identically to cout
but it can be directed to a different destination such as an error log file. cerr
and clog
always write to the same destination.
For more detailed usage, see the <iostream> cout object.
Unlike cout
and clog
, cerr
is not buffered. A buffered output would store the output temporarily in a variable and not write to the destination until certain conditions are met. Buffered outputs are more efficient because they do fewer write operations on files. cerr
is not buffered so that the error messages can be written to a file before the program crashes.
Note: The cerr
object is defined in the <iostream>
header file.
More Examples
Example
Direct cerr
to write to a file instead of to the console:
#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;
}