mbsrtowcs() function in C/C++


In this article we will be discussing the working, syntax and examples of std::mbsrtowcs() function in C++ STL.

What is std::mbsrtowcs()?

std::mbsrtowcs() function is an inbuilt function in C++ STL, which is defined in the <cwchar > header file. mbsrtowcs() means that it converts the null terminated multibyte character string whose first byte is *src to its wide character representation. This function returns the value according to the conversion.

Syntax

size_t mbsrtowcs( wchar_t* pwc, char** str, size_t n, mbstate_t* ps);

Parameters

The function accepts following parameter(s) −

  • pwc − This is the pointer to the location we want the output to be stored.
  • str − Character string which is used as the input.
  • n − It is the number of bytes that are to be checked.
  • ps − It is the pointer to the state object when we are interpreting the multibyte string.

Return value

This function return values differ as per the following condition −

  • 0 − The function will return zero when the character in str which has to be converted is NULL.
  • 1…n− The number of bytes of null ending characters which are converted and stored in string *str.
  • -1 − We get this when there is an error while conversion the errno is set to EILSEQ.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   setlocale(LC_ALL, "en_US.utf8");
   const char* ch = "\u0777\u0755";
   wchar_t arr[20];
   mbstate_t hold = mbstate_t();
   int highest = 10;
   int val = mbsrtowcs ( arr, &ch, highest, &hold );
   wcout << L"Wide characters are: "<< val << endl;
   wcout << L"Given Wide character is: " << arr << endl;
   return 0;
}

Output

Wide characters are: 2
Given Wide character is: ݷݕ

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   setlocale(LC_ALL, "en_US.utf8");
   const char* ch = u8"z\u00df\u6c34";
   wchar_t arr[20];
   mbstate_t hold = mbstate_t();
   int highest = 10;
   int val = mbsrtowcs ( arr, &ch, highest, &hold );
   wcout << L"Total Wide characters are: "<< val << endl;
   wcout << L"Given Wide character is: " << arr << endl;
   return 0;
}

Output

Total Wide characters are: 3
Given Wide character is: zß水


Updated on: 17-Apr-2020

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements