C++ cstdlib mbstowcs

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

The C++ <cstdlib> 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++ cstdlib mbtowc function

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[ strlen( sr )+1 ] ,
wsuni[ strlen( unist )+1 ] ;

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

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

//Passing UTF-8 characters
num1=mbstowcs( wsuni , unist , strlen( unist ) );
cout<< “num1=” << num1 << endl ;
wcout<< 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[ strlen( cns )+1 ];

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

cout<< t << endl;
wcout<< wcns << endl ;

Output in Code::Blocks,


Related links

->C++ wcstombs cstdlib

->C++ mbtowc cstdlib