C/C++ 中的 mbrtoc32() 函式及示例
本文將討論 C++ STL 中 std::mbrtoc32() 函式的工作原理、語法和示例。
什麼是 std::mbrtoc32()?
std::mbrtoc32() 函式是 C++ STL 中的內建函式,定義在 <cuchar> 標頭檔案中。此函式用於將窄多位元組字元轉換為 UTF-32 字元表示。
如果關聯的字元指標不為空,並且所有其他引數也被接受,則它將轉換相應的 32 位字元。
語法
size_t mbrtoc32( char32_t* pc32, char* str, size_t n, mbstate_t* ps);
引數
該函式接受以下引數:
- pc32 − 這是我們希望將輸出儲存到的位置的指標。
- str − 用作輸入的字元字串。
- n − 要檢查的位元組數。
- ps − 當我們解釋多位元組字串時,它是指向狀態物件的指標。
返回值
此函式的返回值根據以下條件而有所不同:
- 0 − 當要轉換的 str 中的字元為空字元時,函式將返回零。
- 1…n − 從字元字串 *str 轉換的多位元組字元的位元組數。
- -3 − 如果存在代理對,這意味著 char32_t 來自多 char32_t。輸入中不應建立任何位元組。
- -2 − 當接下來的 n 個位元組不完整但到目前為止是有效的多位元組字元時,我們將得到 -2。
- -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
廣告