mbrlen() function in C/C++
Last Updated :
05 Sep, 2018
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:
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
Return value : The function returns four value as below:
- 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
Below programs illustrate the above function:
Program 1 :
#include <bits/stdc++.h>
using namespace std;
void check_( const char * str, size_t n)
{
mbstate_t ps = mbstate_t ();
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;
}
int main()
{
setlocale (LC_ALL, "en_US.utf8" );
char str[] = "\u10000b5" ;
check_(str, 1);
check_(str, 6);
return 0;
}
|
Output:
Next 1 byte(s) doesn't represent a complete multibyte character
Next 6 byte(s) of á??0b5holds 3 byte multibyte character
Program 2:
#include <bits/stdc++.h>
using namespace std;
void check_( const char * str, size_t n)
{
mbstate_t ps = mbstate_t ();
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;
}
int main()
{
setlocale (LC_ALL, "en_US.utf8" );
char str[] = "" ;
check_(str, 1);
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...