C++ Standard Library C++ STL Library

C++ <cwchar> - mbrlen() Function



The C++ <cwchar> mbrlen() function returns the size of the multibyte character whose first byte is pointed to by str, examining at most max bytes.

The function uses (and updates) the shift state described by ps. If ps is a null pointer, the function uses its own internal shift state, which is altered as necessary only by calls to this function.

If str is a null pointer, the function resets the shift state (and ignores parameter max).

Syntax

size_t mbrlen(const char *str, size_t max, mbstate_t* ps);

Parameters

str Specify pointer to the multibyte character.
max Specify maximum number of bytes in str that can be examined.
size_t is an unsigned integral type.
ps Specify pointer to the mbstate_t object used when interpreting the multibyte string.

Return Value

Returns zero, if str points to a null character or str is a null pointer.

Otherwise, if at most max characters pointed by str form a valid multibyte character, the function returns the size in bytes of that multibyte character.

Otherwise, if at most max characters do not contribute to form a valid multibyte character, the function returns (size_t)-1 and sets errno to EILSEQ.

Otherwise, if the max characters contribute to an incomplete (but potentially valid) multibyte character, the function returns (size_t)-2.

Example:

In the example below shows the usage of mbrlen() function.

#include <clocale>
#include <cstring>
#include <cwchar>

void print_mb(const char* ch){
  mbstate_t temp1, temp2;   
  int len;
  wchar_t wc;

  int cal = strlen(ch);
  const char* i = ch + cal;

  while ((len = mbrlen(ch, i - ch, &temp1)) > 0){
    mbrtowc(&wc, ch, i - ch, &temp2);
    wprintf(L"Next %i bytes are the character %lc\n", len, wc);
    ch += len;
  }
}

int main(){
  setlocale(LC_ALL, "en_US.utf8");
  const char* str = u8"\xE2\x88\x83y\xE2\x88\x80x\xC2";
  print_mb(str);
  return 0;
}

The output of the above code will be:

Next 3 bytes are the character ∃
Next 1 bytes are the character y
Next 3 bytes are the character ∀
Next 1 bytes are the character x

❮ C++ <cwchar> Library