C programming mbstowcs stdlib.h

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

In C programming the <stdlib.h> mbstowcs converts the multibyte string pointed to by ‘s’ into a wide character string and puts that result in the array pointed to by ‘pwcs’.The declaration of the function is shown below.

pwcs -The wchar_t array that stores the converted multibyte characters.

s -The multibyte characters that is to be converted to wide characters.

n -The the number of multibyte characters that are converted into wide characters.

Return type
    a) If the function execution succeeds the number of bytes that is converted into wide characters is returned without counting the null character.Say if only three bytes or three characters is converted to wide characters,3 will be returned.

    b) If an error occur -1 is returned.

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

Link : C mbtowc stdlib.h

Code example :Include the header >cstring> to use the function ‘strlen’.

char sr[]=”Bunny” ,
unist[]=u8″\u00f3\u00a2\u0019\u0023″ ; ///UTF-8 characters

wchar_t ws[20 ] ,
wsuni[ 20 ] ;

size_t num1=mbstowcs( ws , sr , strlen( sr ) );

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

//Passing UTF-8 characters
num1=mbstowcs( wsuni , unist , strlen( unist ) );
printf(“\n\nnum1=%i \n%ls” ,num1 , ws ) ;

Output in code::blocks,



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 wide character array obtained will not be null terminated if teh returned value is ‘n’;

 iii) No multibyte characters that follow a null character (which is converted into a null wide character) will be examined or converted.For instance,in the multibyte characters “name\0true“, only the characters before ‘\0’ i.e. “name”,is converted to wchar_t type.

Code example :Include the header >cstring> to use the function ‘strlen’.

char cns[]=”name\0true” ;
wchar_t wcns[20 ];

size_t t=mbstowcs( wcns , cns , strlen( cns ) );

printf(“%i \n%ls” ,t ,wcns ) ;

Output in Code::Blocks,


Related links

->C wcstombs stdlib.h

->C programming mblen stdlib.h