C++ Library - <cuchar>



The <cuchar> header in C++ provides a functionality for conversion between the narrow and wide character encodings, particularly for work with UTF-8, UTF-16 and UTF-32 formats. It bridges the gap between the C-style character handling and modern C++ wide character. It ensures that the character data can be efficiently converted between different types.

This header includes the C-standard library <uchar.h> functions, offering a C++ compatible interface. The commonly used C++ <cuchar> copying functions are listed below along with their description.

Including <cuchar> Header

To include the <cuchar> header in your C++ program, you can use the following syntax.

#include <cuchar>

Functions of <cuchar> Header

Below is list of all functions from <cuchar> header.

Sr.No. Functions & Description
1 mbrtoc16

It converts a narrow multibyte character to UTF-16 encoding.

2 c16rtomb

It convert a 16-bit wide character to narrow multibyte string.

Converting Multibyte to Wide string

In the following example, we are going to convert the multibyte string to a wide string.

#include <iostream>
#include <cuchar>
int main() {
   const char * x = "TutorialsPoint";
   wchar_t y[50];
   size_t a = mbstowcs(y, x, sizeof(y) / sizeof(wchar_t));
   if (a != (size_t) - 1) {
      std::wcout <<  "Result : " << y << std::endl;
   } else {
      std::cerr << "Conversion failed!" << std::endl;
   }
   return 0;
}

Output

Output of the above code is as follows −

Result : TutorialsPoint

Calculating Length

Consider the following example, where we are going to get the length of the wide-character string.

#include <iostream>
#include <cuchar>
int main() {
   const wchar_t * x = L "Welcome";
   size_t y = wcslen(x);
   std::wcout << L "Result : " << y << std::endl;
   return 0;
}

Output

Following is the output of the above code −

Result : 7
Advertisements