Cerr — Error Stream Object in C++
Introduction
This article tries to throw some light on (often ignored) cerr
Object in C++. The ‘c’ in cerr means “character” and ‘err’ means “error”, hence cerr means “character error”.
It is defined in iostream
header file and it corresponds to the C stream stderr
. It has a very similar usage to the cout
object (i.e. printing characters on the console during runtime) under the stream stdout
.
The Difference
Even though the result of both cout and cerr is same, there is a very subtle difference between the two which we can find in the use-case of the above both streams.
Here a sample code to show the difference between the two:
#include<bits/stdc++>
using namespace std;
int main()
{cout << "Hey there, Geek! :: cout" << endl;cerr << "Hey there, Geek! :: cerr" << endl;return 0;}
Both the statements above will print characters but under different consoles/context. Have a look at the output.
Output:
Hey there, Geek! :: cout
Runtime Error:
Hey there, Geek! :: cerr
So, what can be derived from their usage?
Generally, stdout::cout
should be used for actual program output, while all information and error messages should be printed to stderr::cerr
.
For example: Let’s say the user wants to open a file and redirect output to that external file. Assume that during the program execution (due to some problem) file opening throws an error. To keep a check of such errors the developer has to log the error somewhere to check it later. He can use cerr
since that error is still printed while not being an ouput to the console or the output file.
Let’s see an example program for that:
#include <iostream>
#include<fstream>
using namespace std;
int main(){char fileName[] = "data.txt";// Opening a file using the infile object of ifstream class in fstream header file
ifstream infile(fileName);// If the file exists, start reading from the fileif(infile)
cout << infile.rdbuf();// If any problem occurs, this message is shown as a error.
// This way, user can clearly diffrenciate between legit output and //errors in their code.else
cerr << "Error while opening the file " << fileName <<endl;return 0;}
Thanks!