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

ฟังก์ชัน mbrtowc() ใน C/C++


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

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

std::mbrtowc() เป็น built-in function ใน C++ STL นิยามใน <cwchar> header file mbrtowc() หมายถึงแปลง narrow multibyte character string เป็น wide character ฟังก์ชันนี้ใช้แปลง narrow multibyte character ให้เป็น wide character representation

Syntax

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

Parameters

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

  • pwc − 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
  • -2 − ได้ -2 เมื่อ next n bytes incomplete แต่จนถึงตอนนี้เป็น valid multibyte character
  • -1 − ได้ -1 เมื่อเจอ encoding error ไม่มีอะไรเขียนไปที่ *pwc

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;
void print_(const char* ch){
    mbstate_t temp = mbstate_t();
    int cal = strlen(ch);
    const char* i = ch + cal;
    int total;
    wchar_t con;
    while ((total = mbrtowc(&con, ch, i - ch, &temp)) > 0){
        wcout << "Next " << total << " bytes are the character " << con << '\n';
        ch += total;
    }
}
int main(){
    setlocale(LC_ALL, "en_US.utf8");
    const char* len = u8"z\u00df\u6c34";
    print_(len);
}

ผลลัพธ์

Next 1 bytes are the character z
Next 2 bytes are the character ß
Next 3 bytes are the character 水

ตัวอย่าง

#include <bits/stdc++.h>
using namespace std;
void print_(const char* ch){
    mbstate_t temp = mbstate_t();
    int cal = strlen(ch);
    const char* i = ch + cal;
    int total;
    wchar_t con;
    while ((total = mbrtowc(&con, ch, i - ch, &temp)) > 0){
        wcout << "Next " << total << " bytes are the character " << con << '\n';
        ch += total;
    }
}
int main(){
    setlocale(LC_ALL, "en_US.utf8");
    const char* len = u8"\xE2\x88\x83y\xE2\x88\x80x\xC2";
    print_(len);
}

ผลลัพธ์

Next 3 bytes are the character ∃
Next 1 bytes are the character y
Next 3 bytes are the character ∀
Next 1 bytes are the character x