C/C++ 程式中的 mbrtowc() 函式
在本文中,我們將討論 C++ STL 中 std::mbrtowc() 函式的工作原理、語法和示例。
什麼是 std::mbrtowc()?
std::mbrtowc() 函式是 C++ STL 中的內建函式,在 <cwchar> 標頭檔案中定義。mbrtowc() 表示它將窄多位元組字元字串轉換為寬字元。此函式用於將窄多位元組字元轉換為寬字元表示形式。
語法
size_t mbrtowc( wchar_t* pwc, char* str, size_t n, mbstate_t* ps);
引數
該函式接受以下引數:
- pwc - 這是我們希望輸出儲存到的位置的指標。
- str - 用作輸入的字元字串。
- n - 要檢查的位元組數。
- ps - 當我們解釋多位元組字串時,它是狀態物件的指標。
返回值
此函式的返回值根據以下條件而有所不同:
- 0 - 當要轉換的 str 中的字元為 NULL 時,函式將返回零。
- 1…n - 從字元字串 *str 轉換的多位元組字元的位元組數。
- -2 - 當接下來的 n 個位元組不完整但到目前為止是一個有效的多位元組字元時,我們將得到 -2。
- -1 - 當我們遇到編碼錯誤時,我們將得到 -1,沒有內容寫入 *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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP