Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

mbrtoc32() ใน C/C++ พร้อมตัวอย่าง


ในบทความนี้ เราจะอภิปรายการทำงาน syntax และตัวอย่างของ std::mbrtoc32() function ใน C++ STL

std::mbrtoc32() คืออะไร?

std::mbrtoc32() เป็น built-in function ใน C++ STL นิยามใน <cuchar> header file ใช้แปลง narrow multibyte character เป็น UTF-32-character representation

ถ้า character pointer ที่เกี่ยวข้องไม่ใช่ null และ parameters อื่นๆ ก็ยอมรับ จะแปลง corresponding 32-bit character

Syntax

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

Parameters

ฟังก์ชันรับ parameter(s) ดังนี้ −

  • pc32 − pointer ไปยังตำแหน่งที่ต้องการเก็บผลลัพธ์
  • str − character string ที่ใช้เป็น input
  • n − จำนวน bytes ที่ต้องตรวจสอบ
  • ps − pointer ไปยัง state object เมื่อ interpret multibyte string

Return value

ฟังก์ชันคืนค่าต่างกันตามเงื่อนไข −

  • 0 − คืน 0 เมื่อ character ใน str ที่ต้องแปลงเป็น NULL
  • 1…n − จำนวน bytes ของ multibyte character ที่แปลงจาก *str
  • -3 − ถ้ามี surrogate pair หมายถึง char32_t มาจาก multi-char32_t ไม่มี bytes จาก input
  • -2 − ได้ -2 เมื่อ next n bytes incomplete แต่เป็น valid multibyte character
  • -1 − ได้ -1 เมื่อเจอ encoding error ไม่มีอะไรเขียนที่ *pc32

ตัวอย่าง

#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);
}

ผลลัพธ์

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

ตัวอย่าง

#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);
}

ผลลัพธ์

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