Mbsinit Function In Cc++

In this article, you will learn about the mbsinit function in C++ with its syntax and examples.

What is the mbsinit function?

In C/C++, the mbsinit function is found in the header of the Standard C Library. If a multibyte conversion state object is not in its initial state, it can be determined using this function. Multibyte character encodings like Shift-JIS and UTF-8 are commonly linked to the multibyte conversion state object.

Syntax:

This is the mbsinit function's prototype:

Example

#include <wchar.h>
int mbsinit(const mbstate_t *ps);
  • ps: A multibyte conversion state objeccpp tutorialer.
  • The function returns non-zero if the multibyte conversion state object that ps points to is in its original state and otherwise it returns zero.
  • Variable-length byte sequences are used in multibyte character encoding to represent characters. The mbsinit function comes in useful when handling stateful conversions and working with multibyte strings. It facilitates figuring out whether or not a conversion state has been initialized.
  • Example:

Let us take an example to illustrate the use of the mbsinit function in C.

Example

#include <wchar.h>
#include <locale.h>
#include <stdio.h>
int main() {
setlocale(LC_ALL, "");
mbstate_t state;
wchar_t wideChar = L'A';
if (mbsinit(&state)) {
printf("Conversion state is initialized.\n");
} else {
printf("Conversion state is not initialized.\n");
}
size_t result = wcrtomb(NULL, wideChar, &state);
if (result == (size_t)-1) {
perror("wcrtomb");
return 1;
}
if (mbsinit(&state)) {
printf("Conversion state is initialized.\n");
} else {
printf("Conversion state is not initialized.\n");
}
return 0;
}

Output:

Explanation:

In this example, the wide-to-multibyte conversion using the wcrtomb function is tested both before and after to see if the multibyte conversion state object (state) is in its initial state using mbsinit. The behavior of multibyte character encoding functions can be impacted by setting the locale to the default locale using the setlocale function.

Example 2:

Let us take an example to illustrate the use of the mbsinit function in C++.

Example

#include <bits/stdc++.h>
using namespace std;
void checkfor(mbstate_t ps)
{
int func = mbsinit(&ps);
if (func)
cout<<"The conversion state is initial conversion state\n";
else
cout<<"The conversion state is not initial conversion state";
}
int main()
{
setlocale(LC_ALL, "en_US.utf8");
char str[] = "\u00df";
mbstate_t ps = mbstate_t();
checkfor(ps);
mbrlen(str, 1, &ps);
checkfor(ps);
return 0;
}

Output:

Input Required

This code uses input(). Please provide values below: