C++ mbrlen()

The mbrlen() function in C++ determines the size in bytes of a multibyte character.

The mbrlen() function is defined in <cwchar> header file.

mbrlen() prototype

size_t mbrlen( const char* s, size_t n, mbstate_t* ps);

The mbrlen() function examines the string whose first byte is pointed to by s and determines its size in bytes for the current conversion state ps. At most n bytes in s is examined.

mbrlen() Parameters

  • s: Pointer to the first byte of multibyte string to examine.
  • n: MAximum number of bytes in s to examine.
  • ps: Pointer to mbstate_t object that defines a conversion state.

mbrlen() Return value

The mbrlen() function returns:

  • The number of bytes that complete a valid multibyte character.
  • 0 if s points to null character.
  • -1 is encoding error occurs.
  • -2 if the next n bytes doesn't represent a complete multibyte character.

Example: How mbrlen() function works?

#include <cwchar>
#include <clocale>
#include <iostream>
using namespace std;

void test_mbrlen(const char *s, size_t n)
	mbstate_t ps = mbstate_t();
	int retVal = mbrlen(s, n, &ps);

	if (retVal == -2)
		cout << "Next " << n << " byte(s) doesn't represent a complete multibyte character" << endl;
	else if (retVal == -1)
		cout << "Next " << n << " byte(s) doesn't represent a valid multibyte character" << endl;
		cout << "Next " << n << " byte(s) of " << s << " holds " << retVal << " byof multibyte character" << endl;

int main()
	setlocale(LC_ALL, "en_US.utf8");
	char str[] = "\u00b5";

	test_mbrlen(str, 1);
	test_mbrlen(str, 5);

	return 0;

When you run the program, the output will be:

Next 1 byte(s) doesn't represent a complete multibyte character
Next 5 byte(s) of µ holds 2 bytes of multibyte character