function
<cstdlib>

wctomb

int wctomb (char* pmb, wchar_t wc);
Convert wide character to multibyte sequence
The wide character wc is translated to its multibyte equivalent and stored in the array pointed by pmb. The function returns the length in bytes of the equivalent multibyte sequence pointed by pmb after the call.

wctomb has its own internal shift state, which is altered as necessary only by calls to this function. A call to the function with a null pointer as pmb resets the state (and returns whether multibyte sequences are state-dependent).

The behavior of this function depends on the LC_CTYPE category of the selected C locale.

Parameters

pmb
Pointer to an array large enough to hold a multibyte sequence.
The maximum length of a multibyte sequence for a character in the current locale is MB_CUR_MAX bytes.
Alternativelly, the function may be called with a null pointer, in which case the function resets its internal shift state to the initial value and returns whether multibyte sequences use a state-dependent encoding.
wc
Wide character of type wchar_t.

Return Value

If the argument passed as pmb is not a null pointer, the size in bytes of the character written to pmb is returned. If there is no character correspondence, -1 is returned.

If the argument passed as pmb is a null pointer, the function returns a nonzero value if multibyte character encodings are state-dependent, and zero otherwise.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* wctomb example */
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* wctomb, wchar_t(C) */

int main() {
  const wchar_t str[] = L"wctomb example";
  const wchar_t* pt;
  char buffer [MB_CUR_MAX];
  int i,length;

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

  return 0;
}

The example prints the multibyte characters that a wide character string translates to, using the selected locale (in this case, the default "C" locale).

Output:

[w][c][t][o][m][b][ ][e][x][a][m][p][l][e]


Data races

The function modifies the array pointed by pmb.
The function also accesses and modifies an internal state object, which may cause data races on concurrent calls to this function (see wcrtomb for an alternative that may use an external state object).
Concurrently changing locale settings may also introduce data races.

Exceptions (C++)

No-throw guarantee: this function throws no exceptions.

If pmb is neither a null pointer nor a pointer to an array long enough for the translated character, it causes undefined behavior.

See also