C++ mbsrtowcs()

The mbsrtowcs() function in C++ converts a narrow multibyte character sequence to a wide character sequence (of type wchar_t).

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

mbsrtowcs() prototype

size_t mbsrtowcs( wchar_t* dest, const char** src, size_t len, mbstate_t* ps );

The mbsrtowcs() function converts the multibyte character string whose first byte is represented by *src to corresponding wide character representation and is stored in the wide character array pointed to by dest. A maximum of len wide characters are written to dest.

The conversion process is similar to calling mbrtowc() repeatedly. The conversion stops if:

  • A multibyte null character was converted and stored. In this case, src is set to null and ps represents initial shift state.
  • An invalid multibyte character was encountered. In this case, src is set to point the beginning of the first unconverted multibyte character.
  • len wide character has been stored in dest. In this case, src is set to point the beginning of the first unconverted multibyte character.

mbsrtowcs() Parameters

  • dest: Pointer to the array where the converted wide character is stored.
  • src: Pointer to pointer to the first multibyte character to convert.
  • len: Maximum number wide character to store.
  • ps: Pointer to the conversion state used when interpreting the multibyte string

mbsrtowcs() Return value

  • On success, the mbsrtowcs() function returns the number of wide characters written to dest excluding the terminating wide null character. If dest is a null pointer, it returns the number of wide characters that would have been written considering unlimited length.
  • On conversion error, -1 is returned and errno is set to EILSEQ.

Example: How mbsrtowcs() function works?

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

int main()
{
	setlocale(LC_ALL, "en_US.utf8");
	
	const char* str = "\u0763\u0757\u077f\u075f";
	wchar_t wstr[20];
	
	mbstate_t ps = mbstate_t();
	int len = 10;
	int retVal;
	
	retVal = mbsrtowcs(wstr, &str, len, &ps);
	wcout << L"Number of wide characters written (excluding L\"\\0\") = " << retVal << endl;
	wcout << L"Wide character = " << wstr << endl;
	
	return 0;
}

When you run the program, the output will be:

Number of wide characters written (excluding L"\0") = 4
Wide character = ݣݗݿݟ