devxlogo

Converting wchar_t to char

Converting wchar_t to char

In addition to the widen() member function, the iostream framework supports the narrow() member function which performs the reverse operation, i.e., converting a wide character to its corresponding char value. The narrow() member function has the following prototype:

 char narrow(char_type c, char deflt) const;

size=3>
The first argument is the wide-char value that is to be converted to char. If the conversion is possible, narrow() returns the corresponding value of c. Otherwise, it returns deflt. Remember that not every wide-char character can be converted to char; wide-char values higher than 255 cannot be represented as char. Therefore, in these cases, narrow returns deflt.
In the following example, the user converts the wide-char letter L’a’ (an uppercase L indicates a wchar_t character) to its char equivalent:

 char c=cin.narrow(L'a', 0); // return 0 if conversion fails

size=3>

devx-admin

Share the Post: