cerr declaration
extern ostream cerr;
It is defined in <iostream> header file.
The cerr
object is ensured to be initialized during or before the first time an object of type ios_base::Init
is constructed. After the cerr
object is constructed, the expression (cerr.flags
& unitbuf
) is non zero, which means that any output sent to these stream objects is immediately flushed to the operating system. Also cerr.tie()
== &cout
i.e. cerr.tie()
returns &cout
which means that cout.flush()
is executed before any output operation on cerr.
The "c" in cerr
refers to "character" and 'err' means "error", hence cerr
means "character error".
The cerr
object is used along with the insertion operator (<<) in order to display a stream of characters. The general syntax is:
cerr << varName;
or
cerr << "Some String";
The extraction operator can be used more than once with a combination of variables, strings and manipulators (like endl):
cerr << var1 << "Some String" << var2 << endl;
Beginner C++ programmers use cout
to display the error using standard output to debug their programs, but it is always good practice to use cerr
to display errors.
This is because instead of showing the error stream to the screen, you can later change the error stream to write the errors to a file.
Example : How cerr works?
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char fileName[] = "data.txt";
ifstream infile(fileName);
if(infile)
cout << infile.rdbuf();
else
cerr << "Error while opening the file " << fileName <<endl;
return 0;
}
When you run the program, the output will be: [if the file could not be opened]
Error while opening the file data.txt