C programming wctomb stdlib.h


int wctomb(char *s , wchar_t wc);

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

Parameters:
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
int
  &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.

Code example

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

//Passing ‘wr’ as the second argument
printf(“%i %i\n”, wctomb( &c[0] , wr ) , (int)c[0] ) ;

//Passing ‘w32’ as the second argument
printf(“%i \n”, wctomb( &c[0] , w32 ) ) ;

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

Output in code::blocks ,

1   89
1
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′ ;

printf( “%i \n&i \n%i”, wctomb( &c[0] , wr ) , wctomb( cpt , wnull ) , wctomb( cpt , wc ) );

Output in Code::Blocks ,

-1
1
0


Related links

->C mblen stdlib.h

->C mbtowc stdlib.h

->C mbstowcs stdlib.h