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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP