C++ wcin

Difference between wcin and cin

cin 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. wcin uses wchar_t(wide character) and is usable for Unicode characters.

wcin declaration

extern wistream wcin;

It is defined in <iostream> header file.

The wcin object is ensured to be initialized during or before the first time an object of type ios_base::Init is constructed. After the wcin object is constructed, wcin.tie() returns &wcout which means that any formatted input operation on wcin forces a call to wcout.flush() if any characters are pending for output.

The "wc" in wcin refers to "wide character" and 'in' means "input", hence wcin means "wide character input". The wcin object is used along with the extraction operator (>>) in order to receive a stream of characters. The general syntax is:

wcin >> varName;

The extraction operator can be used more than once to accept multiple inputs as:

wcin >> var1 >> var2 >> … >> varN;

The wcin object can also be used with other member functions such as getline(), read(), etc. Some of the commonly used member functions are:

  • wcin.get(wchar_t &ch): Reads an wide character and store it in ch.
  • wcin.getline(wchar_t *buffer, int length): Reads a stream of wide characters into the string buffer, It stops when
    • it has read length-1 characters or
    • when it finds an end-of-line character ('\n') or the end of the file.
  • wcin.read(wchar_t *buffer, int n): Reads n bytes (or until the end of the file) from the stream into the buffer.
  • wcin.ignore(int n): Ignores the next n characters from the input stream.
  • wcin.eof(): Returns a nonzero value if the end of file (eof) is reached.

Example 1: wcin with extraction operator:

#include <iostream>

using namespace std;

int main()
{
	wchar_t word[20];
	
	wcout << L"Enter a word: ";
	wcin >> word;
	
	wcout << word;
	return 0;
}

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

Enter a word: kathmandu
kathmandu

Example 2: wcin with member function:

#include <iostream>

using namespace std;

int main()
{
	wchar_t str[50], ch;
	
	wcout << L"Enter a string: ";
	wcin.getline(str, 20);
	
	wcout << L"Enter a character: ";
	wcin.get(ch);
	
	wcout << L"String = " << str << endl;
	wcout << L"Character = " << ch << endl;
	
	return 0;
}

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

Enter a string: program using wcin
Enter a character: h
String = program using wcin
Character = h

Be careful

char16_t and char32_t, which were introduced in C++11 are recommended to be used instead of wchar_t because wchar_t is 16 bit on some systems and 32 bit on some other. This makes it difficult to port.


Also Read:

Did you find this article helpful?