std::c32rtomb
来自cppreference.com
<tbody>
</tbody>
| 在标头 <cuchar> 定义
|
||
std::size_t c32rtomb( char* s, char32_t c32, std::mbstate_t* ps ); |
(C++11 起) | |
转换 UTF-32 字符到其窄多字节表示。
若 s 不是空指针,则函数确定存储 c32 的多字节字符表示所需的字节数(包含任何迁移序列,并考虑当前的多字节转换状态 *ps),并存储多字节字符表示于首元素为 s 所指向的字符数组,按需更新 *ps。此函数至多能写 MB_CUR_MAX 个字符。
若 s 是空指针,则调用等价于对某内部存储 buf 的 std::c32rtomb(buf, U'\0', ps)。
若 c32 是空宽字符 U'\0',则存储空字节,前附恢复到初始迁移状态所需的任何迁移序列,并更新转换状态参数 *ps 以表示初始迁移状态。
此函数所用的多字节字符编码为当前活跃的 C 本地环境所指定。
参数
| s | - | 指向将存储多字节字符的窄字符数组的指针 |
| c32 | - | 要转换的 32 位宽字符 |
| ps | - | 指向转译多字节字符串所用的转换状态对象的指针 |
返回值
成功时,返回写入首元素为 s 所指向的字符数组的字节数(包含任何迁移序列)。此值可为 0,例如在处理多 char32_t 单元序列中的前导 char32_t 单元时(UTF-32 中不出现)。
失败时(若 c32 不是合法的 32 位宽字符),返回 -1,存储 EILSEQ 于 errno,并置 *ps 于未指定状态。
示例
运行此代码
#include <climits>
#include <clocale>
#include <cuchar>
#include <iomanip>
#include <iostream>
#include <string_view>
int main()
{
std::setlocale(LC_ALL, "en_US.utf8");
std::u32string_view strv = U"zß水🍌"; // 或 z\u00df\u6c34\U0001F34C
std::cout << "处理 " << strv.size() << " UTF-32 代码单元: [ ";
for (char32_t c : strv)
std::cout << std::showbase << std::hex << static_cast<int>(c) << ' ';
std::cout << "]\n";
std::mbstate_t state{};
char out[MB_LEN_MAX]{};
for (char32_t c : strv)
{
std::size_t rc = std::c32rtomb(out, c, &state);
std::cout << static_cast<int>(c) << " 转换为 [ ";
if (rc != (std::size_t) - 1)
for (unsigned char c8 : std::string_view{out, rc})
std::cout << +c8 << ' ';
std::cout << "]\n";
}
}
输出:
处理 4 UTF-32 代码单元: [ 0x7a 0xdf 0x6c34 0x1f34c ]
0x7a 转换为 [ 0x7a ]
0xdf 转换为 [ 0xc3 0x9f ]
0x6c34 转换为 [ 0xe6 0xb0 0xb4 ]
0x1f34c 转换为 [ 0xf0 0x9f 0x8d 0x8c ]
参阅
(C++11) |
转换窄多字节字符为 UTF-32 编码 (函数) |
[虚] |
将字符串从 InternT 转换到 ExternT,例如在写入文件时 ( std::codecvt<InternT,ExternT,StateT> 的虚受保护成员函数)
|
c32rtomb 的 C 文档
| |