C++ cerr

The cerr object in C++ is used to print error messages. It is defined in the iostream header file.

Example

#include <iostream>
using namespace std;

int main() {
// print error message cerr << "Error!!";
return 0; } // Output: Error!!

cerr Syntax

The syntax of cerr is:

cerr << var_name;

or

cerr << "Some String";

Here,

  • << is the insertion operator
  • var_name is usually a variable, but can also be an array element or elements of containers like vectors, lists, maps, etc.

cerr with Insertion Operator

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 error messages. For example,

int var1 = 25, var2 = 50;

cerr << var1;
cerr << "Some String";
cerr << var2;

The << operator can be used more than once with a combination of variables, strings, and manipulators (like endl):

cerr << var1 << "Some String" << var2 << endl;

While we can use cout to display errors to debug our programs, it is always good practice to use cerr to display errors.

This is because instead of showing the error stream to the screen, we can later change the error stream to write the errors to a file.


Example: C++ cerr

In this program, we will attempt to read the contents of the file data.txt. Let us assume this file either doesn't exist, or contains some errors that prevent it from opening.

Here, we will use the cerr object to notify the user of this error.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
  string file_name = "data.txt";
  ifstream my_file(file_name);
	
  if(my_file) {
    cout << my_file.rdbuf();
  }
  else {
// print error message cerr << "Error while opening the file " << file_name;
} return 0; }

Output

Error while opening the file data.txt

cerr Prototype

The prototype of cerr as defined in the iostream header file is:

extern ostream cerr;

The cerr object in C++ is an object of class ostream. It is associated with the standard C error output stream stderr.

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() == &cerr i.e. cerr.tie() returns &cerr which means that cerr.flush() is executed before any output operation on cerr.

Did you find this article helpful?