mbrtowc() function in C/C++


This mbrtowc() function is used to convert multibyte sequence to wide character string. This returns the length of the multibyte characters in byte. The syntax is like below.

mbrtowc (wchar_t* wc, const char* s, size_t max, mbstate_t* ps)

The arguments are −

  • wc is the pointer which points where the resulting wide character will be stored.
  • s is the pointer to multibyte character string as input
  • max is the maximum number of bytes in s, that can be examined
  • ps is pointing to the conversion state, when interpreting multibyte string.

Example

#include <bits/stdc++.h>
using namespace std;
void display(const char* s) {
   mbstate_t ps = mbstate_t(); // initial state
   int s_len = strlen(s);
   const char* n = s + s_len;
   int len;
   wchar_t wide_char;
   while ((len = mbrtowc(&wide_char, s, n - s, &ps)) > 0) {
      wcout << "The following " << len << " bytes are for the character " << wide_char << '\n';
      s += len;
   }
}
main() {
   setlocale(LC_ALL, "en_US.utf8");
   const char* str = u8"z\u00cf\u7c38\U00000915";
   display(str);
}

Output

The following 1 bytes are for the character z
The following 2 bytes are for the character Ï
The following 3 bytes are for the character 簸
The following 3 bytes are for the character क

Updated on: 30-Jul-2019

124 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements