mbrtoc16() in C/C++ with Examples


The mbrtoc16() is a built-in function in C/C++ which converts a narrow multibyte character to a 16 bit character representation. It is defined within the uchar.h header file of C++.

Syntax:

ssize_t mbrtoc16( char16_t* pc16, const char* s, size_t n, mbstate_t* ps);

Parameters: The function accepts four mandatory parameter which are described below:

Return Value: The function returns five values as follows:

Below programs illustrate the above function.



Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the
// mbrtoc16() function
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <uchar.h>
#include <wchar.h>
using namespace std;
  
int main(void)
{
    char16_t pc16;
    char s[] = "G";
    mbstate_t ps{};
    int length;
  
    // initializing the function
    length = mbrtoc16(&pc16, s, MB_CUR_MAX, &ps);
  
    if (length < 0) {
        perror("mbrtoc16() fails to convert");
        exit(-1);
    }
  
    cout << "Multibyte string = " << s << endl;
    cout << "Length = " << length << endl;
    printf("16-bit character = 0g%02hd\n", pc16);
}
chevron_right

Output:
Multibyte string = G
Length = 1
16-bit character = 0g71

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the
// mbrtoc16() function
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <uchar.h>
#include <wchar.h>
using namespace std;
  
int main(void)
{
    char16_t pc16;
    char s[] = "";
    mbstate_t ps{};
    int length;
    // initializing the function
    length = mbrtoc16(&pc16, s, MB_CUR_MAX, &ps);
  
    if (length < 0) {
        perror("mbrtoc16() fails to convert");
        exit(-1);
    }
  
    cout << "Multibyte string = " << s << endl;
    cout << "Length = " << length << endl;
    printf("16-bit character = 1e%04xy\n", pc16);
}
chevron_right

Output:
Multibyte string = 
Length = 0
16-bit character = 1e0000y

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
C
Practice Tags :