The mbrlen() function in C/C++ determines the size in bytes, of the remainder of the multibyte character whose first byte is pointed to by str, given the current conversion state ps. The behavior of this function depends on the LC_CTYPE category of the selected C locale.
Syntax:
CPP
CPP
size_t mbrlen( const char* str, size_t n, mbstate_t* ps)Parameters: The function accepts three mandatory parameters which are described below:
- str: specifies the pointer to the first byte of multibyte string to examine
- n: specifies the mAximum number of bytes in s to examine
- ps: specifies the pointer to mbstate_t object that defines a conversion state
- the number of bytes which complete a valid multibyte character
- -1 if encoding error occurs
- 0 if s points to null character
- -2 if the next n bytes are part of a possibly valid multibyte character, which is still incomplete after examining all n bytes
// C++ program to illustrate
// mbrlen() function
#include <bits/stdc++.h>
using namespace std;
// Function to find the size of
// the multibyte character
void check_(const char* str, size_t n)
{
// Multibyte conversion state
mbstate_t ps = mbstate_t();
// number of byte to be saved in returnV
int returnV = mbrlen(str, n, &ps);
if (returnV == -2)
cout << "Next " << n << " byte(s) doesn't"
<< " represent a complete"
<< " multibyte character" << endl;
else if (returnV == -1)
cout << "Next " << n << " byte(s) doesn't "
<< "represent a valid multibyte character" << endl;
else
cout << "Next " << n << " byte(s) of "
<< str << "holds " << returnV << " byte"
<< " multibyte character" << endl;
}
// Driver code
int main()
{
setlocale(LC_ALL, "en_US.utf8");
char str[] = "\u10000b5";
// test for first 1 byte
check_(str, 1);
// test for first 6 byte
check_(str, 6);
return 0;
}
Output:
Program 2:
Next 1 byte(s) doesn't represent a complete multibyte character Next 6 byte(s) of á??0b5holds 3 byte multibyte character
// C++ program to illustrate
// mbrlen() function
// with empty string
#include <bits/stdc++.h>
using namespace std;
// Function to find the size of the multibyte character
void check_(const char* str, size_t n)
{
// Multibyte conversion state
mbstate_t ps = mbstate_t();
// number of byte to be saved in returnV
int returnV = mbrlen(str, n, &ps);
if (returnV == -2)
cout << "Next " << n << " byte(s) doesn't"
<< " represent a complete"
<< " multibyte character" << endl;
else if (returnV == -1)
cout << "Next " << n << " byte(s) doesn't "
<< "represent a valid multibyte character" << endl;
else
cout << "Next " << n << " byte(s) of "
<< str << "holds " << returnV << " byte"
<< " multibyte character" << endl;
}
// Driver code
int main()
{
setlocale(LC_ALL, "en_US.utf8");
char str[] = "";
// test for first 1 byte
check_(str, 1);
// test for first 3 byte
check_(str, 3);
return 0;
}
Output:
Next 1 byte(s) of holds 0 byte multibyte character Next 3 byte(s) of holds 0 byte multibyte character