C++ cstdlib wcstombs

size_t wcstombs(char * restrict s ,
const wchar_t * restrict pwcs ,
size_t n);

The C++ <cstdlib> wcstombs converts the wide-character array pointed to by ‘pwcs’ into its multibyte equivalent characters and puts the result in the array pointed to by ‘s’. Only the first ‘n’ bytes of ‘pwcs’ are converted.

s -The array that stores the multibyte character that is converted from the wide character array pointed by ‘pwcs’.

pwcs -The wide characters array that is to be converted to multibyte string.

n -The number of bytes which is to be converted into multibyte characters.If an error occurs -1 is returned.

Return type
size_t -The number of bytes that has been converted to multibyte characters from array pointed by ‘pwcs’.

***Note each multibyte character is converted as though the function ‘wctomb‘ is called literally,but the conversion state of the ‘wctomb‘ function is not affected.

Link : C++ cstdlib wctomb function

Code example

wchar_t ws[]=L”Corecplusplustutorial.com is the best!” ,
wsutf[]=L”\u0085\0025\u00ab” ; //UTF-8 characters

char ch[ sizeof( ws ) ] ,
st[sizeof( wsutf ) ]=u8″\u00f3\u00a2\u0019\u0023″ ; ///UTF-8 characters

size_t num1=wcstombs( &ch[0] , &ws[0] , sizeof( ws ) );

cout<< “num1=” << num1 << endl ;
wcout<< ch << “\n\n” ;

//Passing UTF-8 characters
num1=wcstombs( &st[0] , &wsutf[0] , sizeof( wsutf) ) ;
cout<< “num1=” << num1 << endl ;
wcout<< st ;

Output in code::blocks,

Corecplusplustutorial.com is the best!


Some points to note

 i) No more than ‘n’ (the third argument) elements will be modified in the array pointed to by ‘pwcs’.If copying takes place between objects that overlap, the behavior is undefined.

 ii) The multibyte character array obtained will not be null terminated if ‘n’ is returned.

 iii) No wide characters that follow a null character (which is converted into a null character) will be examined or converted.For instance,in the wide character string is L”True\u00ab Core\0C++”, only the characters before ‘\0’ i.e. “True\u00ab Core”,is converted to multibyte characters.

Code example

wchar_t wnullc[ ]=L”True\u00ab Core\0C++” ;
char cnullc[ sizeof(wnullc)/2 ] ;

size_t t=mbstowcs( cnulls , wnullc , sizeof( wnullc ) );

cout<< t << endl;
wcout<< cnullc << endl ;

Output in Code::Blocks,

True½ Core

Related links

->C++ mbstowcs cstdlib