C programming wcstombs stdlib.h


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

In C programming the <stdlib.h> 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.

Parameters:
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 wctomb stdlib.h

Code example

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

char ch[50] ,
st[ ]=u8″\u00f3\u00a2\u0019\u0023″ ; ///UTF-8 characters

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

printf( “num1=%i \n%ls” , num1, ch) ;

//Passing UTF-8 characters
num1=wcstombs( &st[0] , &wsutf[0] , sizeof( wsutf) ) ;

printf( “num1=%i \n%ls”, num1 , st );

Output in code::blocks,

num1=38
Corecplusplustutorial.com is the best!

num14
à5½





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 ) );

printf(“%i \nls” t , cnullc ) ;

Output in Code::Blocks,

10
True½ Core


Related links

->C mbstowcs stdlib.h