C Library Function - mbstowcs()
C Standard Library - <stdlib.h>
Description
The C library function sizet mbstowcs(wchart *pwcs, const char *str, size_t n) converts the multibyte character string pointed to by the argument str into the array pointed to by pwcs.
Declaration
Below is the declaration for the mbstowcs() function.
size_t mbstowcs(wchar_t* dst, const char* src, std::size_t len);
Parameters
dst -- Pointer to an array of wchar_t elements, large enough to store a wide string with the maximum character length.
src -- The multibyte character string to be converted.
len -- The maximum number of characters to be converted.
Return Value
The function returns the number of converted characters, not including the terminating null character. If an invalid multibyte character is encountered, it returns -1.
Example
The following example demonstrates the use of the mbstowcs() function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int len;
char *pmbnull = NULL;
char *pmb = (char *)malloc( MB_CUR_MAX );
wchar_t *pwc = L"Hi";
wchar_t *pwcs = (wchar_t *)malloc( sizeof( wchar_t ));
printf("Converting to multibyte string\n");
len = wcstombs( pmb, pwc, MB_CUR_MAX);
printf("Characters converted %d\n", len);
printf("Hexadecimal value of the first multibyte character: %#.4x\n", pmb);
printf("Converting back to wide-character string\n");
len = mbstowcs( pwcs, pmb, MB_CUR_MAX);
printf("Characters converted %d\n", len);
printf("Hexadecimal value of the first wide character: %#.4x\n\n", pwcs);
return(0);
}
Let's compile and run the above program, which will produce the following result:
Converting to multibyte string
Characters converted 1
Hexadecimal value of the first multibyte character: 0x19a60010
Converting back to wide-character string
Characters converted 1
Hexadecimal value of the first wide character: 0x19a60030