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;


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

See also  lenso.ai - an AI reverse image search platform
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist