C++ wcstombs()

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

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

wcstombs() prototype

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

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

This function converts the wide character string whose first element is pointed by src to its multibyte representation.

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

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

  • A null character is encountered, which is then converted and stored.
  • A wchar_t was found that does not correspond to a valid character in the current C locale.
  • max number of wide characters has been converted.

wcstombs() Parameters

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

wcstombs() Return value

  • If the conversion is successful, wcstombs() returns the number of multibyte 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 wcstombs() function works?

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

int main()
{
	wchar_t src[] = L"Welcome To Programiz.com";
	char dest[50];
	int num;

	num = wcstombs(dest, src, 50);
	cout << "Number of wide character converted = " << num << endl;
	cout << "Multibyte Character String = " << dest << endl;
	
	return 0;
}

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

Number of wide character converted = 24
Multibyte Character String = Welcome To Programiz.com