mbrtoc32() in C/C++ with Examples

CC++Server Side ProgrammingProgramming

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

What is std::mbrtoc32()?

std::mbrtoc32() function is an inbuilt function in C++ STL, which is defined in <cuchar> header file. This function is used to convert a narrow multibyte character to UTF-32-character representation.

If the associated character pointer is not null, and all other parameters are also accepted then it will convert the corresponding 32-bit character.

Syntax

size_t mbrtoc32( char32_t* pc32, char* str, size_t n, mbstate_t* ps);

Parameters

The function accepts following parameter(s) −

  • pc32 − 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 multibyte character which are converted from the character string *str.
  • -3 − If there is a surrogate pair means, the char32_t is from a multi-char32_t. No bytes are to be made from the input.
  • -2 − We will get -2 when next n bytes incomplete but so far is valid multibyte character.
  • -1 − We get -1 when we face an encoding error, nothing is written to *pc32.

Example

 Live Demo

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <uchar.h>
#include <wchar.h>
using namespace std;
int main(void) {
   char32_t hold;
   char str[] = "I";
   mbstate_t arr{};
   int len;
   // initializing the function
   len = mbrtoc32(&hold, str, MB_CUR_MAX, &arr);
   if (len < 0) {
      perror("conversion failed");
      exit(-1);
   }
   cout << "String is: " << str << endl;
   cout << "Length is: " << len << endl;
   printf("32-bit character = 0g%02hd\n", hold);
}

Output

String is: I
Length is: 1
32-bit character = 0g73

Example

 Live Demo

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <uchar.h>
#include <wchar.h>
using namespace std;
int main(void){
   char32_t hold;
   char str[] = "I";
   mbstate_t arr{};
   int len;
   // initializing the function
   len = mbrtoc32(&hold, str, MB_CUR_MAX, &arr);
   if (len < 0){
      perror("conversion failed");
      exit(-1);
   }
   cout << "String is: " << str << endl;
   cout << "Length is: " << len << endl;
   printf("32-bit character = 0x%08hx\n", hold);
}

Output

String is: I
Length is: 1
32-bit character = 0x0x000000490
raja
Published on 17-Apr-2020 13:23:23
Advertisements