C++ cstdlib wctomb

int wctomb(char *s , wchar_t wc);

The C++ <cstdlib> wctomb function converts the wide character in ‘wc’ to the corresponding multibyte character and stores it in the array pointed by ‘s’.The declaration of the function is shown below.

s -The multi-byte array to store the character that is converted from the ‘wc’ argument.

wc -The wide character that is to be converted to the multi-byte type.

Return type
  &nbsp a) If the execution is successful it returns the number of bytes that is converted to the multi-byte character at a time,mostly 1.
  &nbsp b) If ‘wc’ is a null wide character,a null byte is stored,preceded by any shift sequence needed to restore the initial shift state,and the function is left in the initial conversion state.
  &nbsp c)If ‘s’ is null, then wctomb( ) returns nonzero,if the multibyte character has state-dependent encodings and zero if it does not.
  &nbsp d)If the function execution failed,it returns -1.

Some points to note:

  i)At most the maximum number of characters that can be stored in ‘s’ array is MB_CUR_MAX.

  ii) The implementation behave as if no library function calls the ‘wctomb’ function.

Link : C++11 auto keyword

Code example

char c[5] ;
wchar_t wr=L’Y’ ,
w32=L’\u0000a123′ ; ///assigning char32_t type value

//Passing ‘wr’ as the second argument
cout<< wctomb( &c[0] , wr ) << endl
<< c[0] << “\n\n” ;

//Passing ‘w32’ as the second argument
cout<< wctomb( &c[0] , w32 ) << endl ;

for( auto i=0 ; i<strlen(c) ; i++ ) //include <cstring> to use the function strlen( )
cout<< “c[” << i << “]=” << (int)c[i] << ” ” ;

Output in code::blocks ,


c[0]=51 c[1]=4 c[2]=65

In Visual Studio the code ‘wctomb( &c[0] , w32 )‘ gives the error “‘wctomb’:This function or variable may be unsafe.Consider using wctomb_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS.See online help for details.“.So,it may not compiler.

One more code example is given below to test the return value at various cases.

Code example:

char c[3] ,
cpt=nullptr ;

wchar_t wc=L’U’ ,
wr=L’ш’ , //a Russian character
wnull=L’\0′ ;

cout<< wctomb( &c[0] , wr ) << endl
<< wctomb( cpt , wnull ) << endl
<< wctomb( cpt , wc ) ;

Output in Code::Blocks ,