C++ Standard Library C++ STL Library

C++ <cstdlib> - wctomb() Function



The C++ <cstdlib> wctomb() function converts a wide character wchar to its multibyte encoding and stores it in the char array whose first element is pointed to by str. The function returns the length in bytes of the equivalent multibyte sequence pointed by str.

This function has its own internal shift state, which is altered as necessary only by calling it. If str is a null pointer, it resets its internal conversion state to represent the initial shift state and returns whether multibyte encoding is state-dependent.

Syntax

int wctomb(char *str, wchar_t wchar)

Parameters

str Specify pointer to the character array for output.
wchar Specify wide character to convert.

Return Value

When str is not a null pointer, it returns the number of bytes that are contained in the multibyte character or -1 if wchar is not a valid character.

When str is a null pointer, it returns 0 if the current multibyte encoding is not state-dependent or a non-zero value if the current multibyte encoding is state-dependent.

Example:

In the example below, mblen() and wctomb() functions are used in the user-defined function printbuffer(), which prints a multibyte string character by character.

#include <cstdio>
#include <cstdlib>

int main (){
  wchar_t wchar[] = L"Hello World!";
  const wchar_t* pt;
  char buffer [MB_CUR_MAX];
  int length;

  pt = wchar;
  while(*pt) {
    length = wctomb(buffer, *pt);
    if (length < 1) 
      break;
    printf("[%c]", buffer[0]);
    pt++;
  }

  return 0;
}

The output of the above code will be:

[H][e][l][l][o][ ][W][o][r][l][d][!]

❮ C++ <cstdlib> Library