C++ wcerr

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

Difference between cerr and wcerr

cerr uses char(narrow character) as character type. It can be used for ASCII and ANSI characters.

For internationalization, we need Unicode strings which do not fit in char. wcerr uses wchar_t(wide character) and usable for Unicode characters.

Difference between wcout and wcerr

Beginner C++ programmers use cout and wcout to display the error using standard output to debug their programs, but it is always good practice to use cerr and wcerr 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.

wcerr declaration

extern wostream wcerr;

It is defined in <iostream> header file.

The wcerr object is ensured to be initialized during or before the first time an object of type ios_base::Init is constructed. After the wcerr object is constructed, the expression (wcerr.flags & unitbuf) is non zero, which means that any output sent to these stream objects is immediately flushed to the operating system. Also wcerr.tie() == &wcout i.e. wcerr.tie() returns &wcout which means that wcout.flush() is executed before any output operation on wcerr.

The "wc" in wcerr refers to "wide character" and 'err' means "error", hence wcerr means "wide character error". The wcerr object is used along with the insertion operator (<<) in order to display a stream of characters. The general syntax is:

wcerr << varName;

or

wcerr << "Some String";

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

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

Example : How wcerr works?

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	char fileName[] = "data.txt";
	wifstream infile(fileName);
	
	if(infile)
		wcout << infile.rdbuf(); 
	else
		wcerr << "Error while opening the file " << fileName << endl; 
        return;
}

When you run the program, the output will be: [if the file could not be opened]

Error while opening the file data.txt

Check these related library functions as well: