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