wcrtomb() function in C/C++
The wcrtomb() function in C/C++ converts a wide character to its narrow multibyte representation. The wide character wc is translated to its multibyte equivalent and stored in the array pointed by s. The function returns the length in bytes of the equivalent multibyte sequence pointed by s.
Syntax :
size_t wcrtomb( char* s, wchar_t wc, mbstate_t* ps )
Parameters:The function accepts three mandatory parameters which are described below:
- s: specifies the pointer to an array large enough to hold a multibyte sequence
- wc: specifies the wide character to convert.
- ps: specifies the pointer to the conversion state used when interpreting the multibyte string
Return values: The function returns two value as below:
- On success, it returns the number of bytes written to the character array whose first element is pointed to by s.
- Otherwise, it returns -1 and errno is set to EILSEQ.
Below programs illustrate the above function:
Program 1:
// C++ program to illustrate the // wcrtomb() function #include <bits/stdc++.h> using namespace std; int main() { setlocale (LC_ALL, "en_US.utf8" ); // initialize the string wchar_t wc[] = L "z\u00df\u6c34\U0001f34c" ; // array large enough to hold a multibyte sequence char s[25]; int returnV; // initial state mbstate_t ps = mbstate_t (); for ( int i = 0; i < wcslen(wc); i++) { returnV = wcrtomb(s, wc[i], &ps); // print byte size, if its a valid character if (returnV != -1) cout << "Size of " << s << " is " << returnV << " bytes" << endl; else cout << "Invalid wide character" << endl; } return 0; } |
Output:
Size of z is 1 bytes Size of Ã? is 2 bytes Size of æ°´ is 3 bytes Size of ð?? is 4 bytes
Program 2 :
// C++ program to illustrate the // wcrtomb() function #include <bits/stdc++.h> using namespace std; int main() { setlocale (LC_ALL, "en_US.utf8" ); // initialize the string wchar_t wc[] = L "u\u00c6\u00f5\u01b5" ; // array large enough to hold a multibyte sequence char s[20]; int returnV; // initial state mbstate_t ps = mbstate_t (); for ( int i = 0; i < wcslen(wc); i++) { returnV = wcrtomb(s, wc[i], &ps); // print byte size, if its a valid character if (returnV != -1) cout << "Size of " << s << " is " << returnV << " bytes" << endl; else cout << "Invalid wide character" << endl; } return 0; } |
Output:
Size of u Ì_e is 1 bytes Size of Ã?Ì_e is 2 bytes Size of õÌ_e is 2 bytes Size of ƵÌ_e is 2 bytes
Contact Us