C++ wcrtomb()

The wcrtomb() function in C++ converts a wide character to its narrow multibyte representation.

The wcrtomb() is defined in <cwchar> header file.

wcrtomb() prototype

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.
  • If wc == L'\0', a null byte is stored.

wcrtomb() Parameters

  • 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?

#include <cwchar>
#include <clocale>
#include <iostream>
using namespace std;

int main()
	setlocale(LC_ALL, "en_US.utf8");
	wchar_t str[] = L"u\u00c6\u00f5\u01b5";
	char s[16];
	int retVal;
	mbstate_t ps = mbstate_t();
	for (int i=0; i<wcslen(str); i++)
		retVal = wcrtomb(s, str[i], &ps);
		if (retVal!=-1)
		cout << "Size of " << s << " is " << retVal << " bytes" << endl;
		cout << "Invalid wide character" << endl;
	return 0;

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
Did you find this article helpful?