The wcrtomb() function in C++ converts a wide character to its narrow multibyte representation.
The wcrtomb() is defined in <cwchar> header file.
size_t wcrtomb( char* s, wchar_t wc, mbstate_t* ps );
The wcrtomb() function converts the wide character represented by wc to a narrow multibyte character and is stored in the address pointed to by s.
- If s is not a null pointer, the wcrtomb() function determines the maximum number of bytes required to store the multibyte representation of wc and stores it in the memory location pointed to by s. A maximum of MB_CUR_MAX bytes can be written. The value of ps is updated as required.
- If s is a null pointer, the call is equivalent to
wcrtomb(buf, L'\0', ps) for some internal buffer buf.
wc == L'\0', a null byte is stored.
- s: Pointer to the multibyte character array to store the result.
- wc: Wide character to convert.
- ps: Pointer to the conversion state used when interpreting the multibyte string
wcrtomb() Return value
- On success, the wcrtomb() function returns the number of bytes written to the character array whose first element is pointed to by s.
- On failure (i.e. wc is not a valid wide character), it returns -1, errno is set to EILSEQ and leaves *ps in unspecified state.
Example: How wcrtomb() function works?
using namespace std;
wchar_t str = L"u\u00c6\u00f5\u01b5";
mbstate_t ps = mbstate_t();
for (int i=0; i<wcslen(str); i++)
retVal = wcrtomb(s, str[i], &ps);
cout << "Size of " << s << " is " << retVal << " bytes" << endl;
cout << "Invalid wide character" << endl;
When you run the program, the output will be:
Size of u is 1 bytes
Size of Æ is 2 bytes
Size of õ is 2 bytes
Size of Ƶ is 2 bytes