Join our newsletter for the latest updates.

C++ mbstowcs()

The mbstowcs() function in C++ converts a multibyte character string to equivalent wide character sequence.

The mbstowcs() function is defined in <cstdlib> header file.

mbstowcs() prototype

size_t mbstowcs (wchar_t* dest, const char* src, size_t max);

The mbstowcs() function takes three arguments and returns an integer value.

This function converts the multibyte character string whose first element is pointed by src to its wide character (value of type wchar_t) representation.

The result is stored at the memory location pointed by dest. The parameter max represents the maximum number of multibyte characters to be converted.

The conversion mechanism is same as that of mbtowc(), except that the mbtowc conversion state is unaffected. The conversion stops if:

  • A null character is encountered, which is then converted and stored.
  • An invalid multibyte character is encountered.
  • max number of multibyte characters has been converted.

mbstowcs() Parameters

  • dest: Pointer to the resulting wide character array.
  • src: Pointer to the first element of the multibyte character which is converted to wide character.
  • max: Maximum number of multibyte characters to be converted.

mbstowcs() Return value

  • If the conversion is successful, mbstowcs() returns the number of wide characters excluding the terminating character (i.e. '\0') that is written to the destination array.
  • If any error occurs during conversion, it returns -1.

Example : How mbstowcs() function works?

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
	char src[] = "\xc4\xe3\xba\xc3";
	wchar_t dest[10];
	int num;

	num = mbstowcs(dest, src, MB_CUR_MAX);
	cout << "Number of wide character converted = " << num << endl;
	wcout << "Wide Character String = " << dest << endl;

	return 0;

When you run the program, a possible output will be:

Number of wide character converted = 1
Wide Character String = ─