ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน std::mbrtoc32() ใน C++ STL
std::mbrtoc32() คืออะไร
ฟังก์ชัน std::mbrtoc32() เป็นฟังก์ชัน inbuilt ใน C++ STL ซึ่งกำหนดไว้ในไฟล์ส่วนหัว
หากตัวชี้อักขระที่เกี่ยวข้องไม่เป็นค่าว่าง และพารามิเตอร์อื่นๆ ทั้งหมดได้รับการยอมรับด้วย ตัวชี้จะแปลงอักขระ 32 บิตที่สอดคล้องกัน
ไวยากรณ์
size_t mbrtoc32( char32_t* pc32, char* str, size_t n, mbstate_t* ps);
พารามิเตอร์
ฟังก์ชันยอมรับพารามิเตอร์ต่อไปนี้ -
- pc32 − นี่คือตัวชี้ไปยังตำแหน่งที่เราต้องการให้จัดเก็บเอาต์พุต
- str − สตริงอักขระที่ใช้เป็นอินพุต
- น − เป็นจำนวนไบต์ที่ต้องตรวจสอบ
- ป.ล. − เป็นตัวชี้ไปยังอ็อบเจ็กต์สถานะเมื่อเราแปลสตริงแบบหลายไบต์
คืนค่า
ค่าที่ส่งกลับของฟังก์ชันนี้แตกต่างกันตามเงื่อนไขต่อไปนี้ -
- 0 − ฟังก์ชันจะคืนค่าศูนย์เมื่ออักขระใน str ที่ต้องแปลงเป็น NULL
- 1…n − จำนวนไบต์ของอักขระแบบหลายไบต์ซึ่งถูกแปลงจากสตริงอักขระ *str.
- -3 − หากมีตัวแทนตัวแทนหมายถึง char32_t มาจาก multi-char32_t ไม่ต้องสร้างไบต์จากอินพุต
- -2 − เราจะได้ -2 เมื่อ n ไบต์ถัดไปไม่สมบูรณ์ แต่จนถึงตอนนี้เป็นอักขระแบบหลายไบต์ที่ถูกต้อง
- -1 − เราได้รับ -1 เมื่อเราพบข้อผิดพลาดในการเข้ารหัส ไม่มีอะไรถูกเขียนลงใน *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