wctomb - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# wctomb

From cppreference.com
< c‎ | string‎ | multibyte

Defined in header `<stdlib.h>` |  |
int wctomb( char* s, wchar_t wc ); |  |

Converts a wide character `wc` to multibyte encoding and stores it (including any shift sequences) in the char array whose first element is pointed to by `s`. No more than MB_CUR_MAX characters are stored.

If `wc` is the null character, the null byte is written to `s`, preceded by any shift sequences necessary to restore the initial shift state.

If `s` is a null pointer, resets the global conversion state and determines whether shift sequences are used.

### [edit] Notes

Each call to `wctomb` updates the internal global conversion state (a static object of type mbstate_t, only known to this function). If the multibyte encoding uses shift states, this function is not reentrant. In any case, multiple threads should not call `wctomb` without synchronization: wcrtomb may be used instead.

### [edit] Parameters

s | - | pointer to the character array for output
wc | - | wide character to convert

### [edit] Return value

If `s` is not a null pointer, returns the number of bytes that are contained in the multibyte representation of `wc` or -1 if `wc` is not a valid character.

If `s` is a null pointer, resets its internal conversion state to represent the initial shift state and returns ​0​ if the current multibyte encoding is not state-dependent (does not use shift sequences) or a non-zero value if the current multibyte encoding is state-dependent (uses shift sequences).

### [edit] Example

Run this code

    #include <stdio.h>
    #include <stdlib.h>
    #include <locale.h>

    void demo(wchar_t wc)
    {
        printf("State-dependent encoding?   %d\n", wctomb(NULL, wc));

        char mb[MB_CUR_MAX];
        int len = wctomb(mb,wc);
        printf("wide char '%lc' -> multibyte char '", wc);
        for (int idx = 0; idx < len; ++idx)
            printf("%#2x ", (unsigned char)mb[idx]);
        printf("'\n");
    }

    int main ()
    {
        setlocale(LC_ALL, "en_US.utf8");
        printf("MB_CUR_MAX = %zu\n", MB_CUR_MAX);
        demo(L'A');
        demo(L'\u00df');
        demo(L'\U0001d10b');
    }

Output:

    MB_CUR_MAX = 6
    State-dependent encoding?   0
    wide char 'A' -> multibyte char '0x41 '
    State-dependent encoding?   0
    wide char 'ß' -> multibyte char '0xc3 0x9f '
    State-dependent encoding?   0
    wide char '𝄋' -> multibyte char '0xf0 0x9d 0x84 0x8b '

### [edit] See also

mbtowc | converts the next multibyte character to wide character (function) [edit]
wcrtomb | converts a wide character to its multibyte representation, given state (function) [edit]
C++ documentation for wctomb

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=c/string/multibyte/wctomb&oldid=67318"