Standard Error Stream Object - cerr in C++
The standard error stream in C++ is a special output stream used to display error messages or warnings. It is represented by std::cerr and sends messages to the screen, just like std:: cout . However, unlike std:: cout, it is unbuffered, meaning it shows messages immediately. This helps in debugging by showing errors right away, even if the program crashes.
Example:
#include <iostream>
using namespace std;
int main() {
// Printing message immediately to the console- unbuffered
cerr << "Welcome to GfG! :: cerr\n";
// Printing after the program execution completes- buffered
cout << "Welcome to GfG! :: cout";
return 0;
}
Error
Welcome to GfG! :: cerr
Welcome to GfG! :: cout
Buffered vs Unbuffered Output
A buffer is like a temporary storage area ( a "waiting room") for data before it is shown or written.
Feature | Buffered Output | Unbuffered Output |
---|---|---|
What it does | Stores output in memory temporarily | Sends output directly (immediately) |
When it shows up | Shows later (when buffer is full or flushed) | Shows immediately |
Used by | std::cout, std::clog | std::cerr |
Use case | For regular output (not urgent) | For errors or important messages |
What is Redirection?
Redirection means sending output (like messages or errors) to a different place instead of the screen.
Normally, when we run a C++ program.
- std:: cout (normal output) and
- std:: cerr (error output)
both print to the screen ( called the console or terminal).
But with redirection, we can tell our program:
"Send the output somewhere else, like a file."
Redirection of std::cerr (Error Messages)
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// This will go to the console
cout << "This is normal output (cout).\n";
// This will be redirected to a file
cerr << "This is an error message (cerr).\n";
return 0;
}
In the file error_log.txt:
This is an error message written to a file.
How to Compile and Run with Redirection
g++ main.cpp -o myprogram # Compile the program
./myprogram 2> error_log.txt # Run the program and redirect std::cerr to a file
Output on Screen:
This is normal output (cout).
Why Redirect std::cerr?
- Saves Errors: So we can check them later, especially if our program crashes.
- Log files: Useful for programs that run often (like servers or scripts).
- Keep things separate: Separate normal results from error messages for clarity.
- Debugging: Helps track down what went wrong and when.