ฟังก์ชัน mbrtowc() นี้ใช้เพื่อแปลงลำดับหลายไบต์เป็นสตริงอักขระแบบกว้าง ส่งคืนความยาวของอักขระหลายไบต์ในหน่วยไบต์ ไวยากรณ์เป็นเหมือนด้านล่าง
mbrtowc (wchar_t* wc, const char* s, size_t max, mbstate_t* ps)
อาร์กิวเมนต์คือ −
- wc คือพอยน์เตอร์ซึ่งชี้ตำแหน่งที่จะเก็บอักขระแบบกว้างที่ได้ผลลัพธ์ไว้
- s เป็นตัวชี้ไปยังสตริงอักขระหลายไบต์เป็นอินพุต
- max คือจำนวนไบต์สูงสุดในหน่วย s ที่ตรวจสอบได้
- ps กำลังชี้ไปที่สถานะการแปลง เมื่อแปลสตริงแบบหลายไบต์
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
void display(const char* s) {
mbstate_t ps = mbstate_t(); // initial state
int s_len = strlen(s);
const char* n = s + s_len;
int len;
wchar_t wide_char;
while ((len = mbrtowc(&wide_char, s, n - s, &ps)) > 0) {
wcout << "The following " << len << " bytes are for the character " << wide_char << '\n';
s += len;
}
}
main() {
setlocale(LC_ALL, "en_US.utf8");
const char* str = u8"z\u00cf\u7c38\U00000915";
display(str);
} ผลลัพธ์
The following 1 bytes are for the character z The following 2 bytes are for the character Ï The following 3 bytes are for the character 簸 The following 3 bytes are for the character क