C++ wcout

Difference between wcout and cout

cout users 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. wcout uses wchar_t(wide character) and usable for Unicode characters.

wcout declaration

extern wostream wcout;

It is defined in <iostream> header file.

The wcout object is ensured to be initialized during or before the first time an object of type ios_base::Init is constructed. After the wcout object is constructed, it is tied to wcin which means that any input operation on wcin executes wcout.flush().

The "wc" in wcout refers to "wide character" and 'out' means "output", hence wcout means "wide character output".

The wcout object is used along with the insertion operator (<<) in order to display a stream of characters. The general syntax is:

wcout << varName;

or

wcout << "Some String";

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

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

The wcout object can also be used with other member functions such as put(), write(), etc. Some of the commonly used member functions are:

  • wcout.put(wchar_t &ch): Displays the wide character stored by ch.
  • wcout.write(wchar_t *str, int n): Displays the first n character reading from str.
  • wcout.setf(option): Sets a given option. Commonly used options are left, right, scientific, fixed, etc.
  • wcout.unsetf(option): Unsets a given option.
  • wcout.precision(int n): Sets the decimal precision to n while displaying floating-point values. Same as wcout << setprecision(n).

Example 1: wcout with insertion operator:

#include <iostream>

using namespace std;

int main()
{
	int x, y;
	wchar_t str[20];
	wcout << L"Enter 2 integers:";
	wcin >> x >> y;
	wcout << L"Sum = " << (x+y) << endl;
	
	wcout << L"Enter a string:";
	wcin >> str;
	wcout << "You entered " << str;
	return 0;
}

When you run the program, a possible output will be:

Enter 2 integers:4 9
Sum = 13
Enter a string:today
You entered today

Example 2: wcout with member function:

#include <iostream>

using namespace std;

int main()
{
	wchar_t str[] = L"Learn C++ by examples";
	wchar_t ch = 'x';
	
	wcout.write(str,9);
	wcout << endl;
	wcout.put(ch);
	
	return 0;
}

When you run the program, the output will be:

Learn C++
x