C programming stdlib.h function - int mbtowc(whcar_t *pwc, const char *str, size_t n)

www.igift‮di‬ea.com

The mbtowc function in the stdlib.h header file of C programming language converts a multibyte sequence to a wide character.

The function has the following syntax:

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

Here, pwc is a pointer to a wide character where the result will be stored. str is a pointer to the multibyte sequence to be converted, and n is the maximum number of bytes to be examined.

The function returns the number of bytes that were examined in the multibyte sequence. If an invalid multibyte sequence is encountered, it returns -1. If the str argument is a null pointer, the function returns 0.

Here is an example usage of the mbtowc function:

#include <stdlib.h>
#include <stdio.h>
#include <wchar.h>

int main() {
    char *mbstring = "hello";
    wchar_t wc;
    int res = mbtowc(&wc, mbstring, 2);
    if (res > 0) {
        wprintf(L"First wide character: %lc\n", wc);
    }
    return 0;
}

In this example, the mbtowc function converts the first two bytes of the multibyte string "hello" to a wide character. The resulting wide character is then printed to the console using the wprintf function.