w3resource

C mbtowc() function

C mbtowc() function - Convert a character to a wide-character code

Syntax mbtowc() function

int mbtowc(whcar_t *pwc, const char *str, size_t n)

The mbtowc() function is used to first determine the length of the multibyte character pointed to by string. As described in mbstowcs, the multibyte character is then converted into a wide character. A maximum of n bytes are examined.

Parameters mbtowc() function

Name Description Required /Optional
pwc Address of a wide character (type wchar_t). Required
str Address of a sequence of bytes (a multibyte character). Required
n Number of bytes to check. Required

Return value from mbtowc()

If string is NULL:

  • Nonzero when the active locale is mixed byte.
  • 0 otherwise.

If string is not NULL:

  • The number of bytes that make up the converted multibyte character.
  • 0 if string points to the null character.
  • -1 if string does not point to a valid multibyte character.

Example: mbtowc() function

The following example shows the usage of mbtowc() function.

#include <stdio.h>
#include <stdlib.h>
#include <locale.h> 
#define LOCNAME "qsys.lib/mylib.lib/ja_jp959.locale"
/*Locale created from source JA_JP and CCSID 939 */
 
int length, temp;
char string [] = "\x0e\x41\x71\x0f\x41";
wchar_t text[6];
 
int main(void)
{
   /* initialize internal state variable */
   temp = mbtowc(text, NULL, 0);            
   setlocale(LC_ALL, LOCNAME);
   /* Set string to point to a multibyte character. */
   length = mblen(string, MB_CUR_MAX);
   temp = mbtowc(text,string,length);
   text[1] = L'\0';
   printf("Wide character string: %ls",text);
}

Output:

Wide character string: ♫

C Programming Code Editor:

Previous C Programming: C mbstowcs()
Next C Programming: C wcstombs()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
{
    ptr = 0;// oops, I meant *ptr = 0
}

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q