In C++, we can use 16-bit character representations. The c16rtomb() function is used to convert 16-bit character representation to narrow multi-byte character representation. We can find this function inside the uchar.h header file.
This function takes three parameters. These are −
- The string where multi-byte character will be stored
- 16-bit character to convert
- The pointer of type mbstate_t object. which is used to interpret multibyte string.
This function returns number of bytes written to the character array, when it is successful, otherwise returns -1. Let us see an example to get better idea.
Example
#include <iostream> #include <uchar.h> #include <wchar.h> using namespace std; int main() { const char16_t myStr[] = u"Hello World"; char dest[50]; mbstate_t p{}; size_t length; int j = 0; while (myStr[j]) { length = c16rtomb(dest, myStr[j], &p); //get length from c16rtomb() method if ((length == 0) || (length > 50)) break; for (int i = 0; i < length; ++i) cout << dest[i]; j++; } }
Output
Hello World