命名空间
变体
操作

std::c32rtomb

来自 cppreference.cn
< cpp‎ | string‎ | multibyte
定义于头文件 <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 是空指针,则此调用等效于 std::c32rtomb(buf, U'\0', ps),其中 buf 为某个内部缓冲区。

如果 c32 是空宽字符 U'\0',则会存储一个空字节,其前导是任何恢复初始移位状态所需的移位序列,并且转换状态参数 *ps 将更新为表示初始移位状态。

此函数使用的多字节编码由当前活动的 C 语言环境指定。

目录

[edit] 参数

s - 指向将存储多字节字符的窄字符数组的指针
c32 - 要转换的 32 位字符
ps - 指向解释多字节字符串时使用的转换状态对象的指针

[edit] 返回值

成功时,返回写入到以 s 指向的首元素的字符数组的字节数(包括任何移位序列)。此值可能为 0,例如,当处理多 char32_t 字符序列中的第一个 char32_t 时(UTF-32 中不会发生)。

失败时(如果 c32 不是有效的 32 位字符),返回 -1,在 EILSEQ 中存储 errno,并将 *ps 保留在未指定状态。

[edit] 示例

#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ß水🍌"; // or z\u00df\u6c34\U0001F34C
    std::cout << "Processing " << strv.size() << " UTF-32 code units: [ ";
    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) << " converted to [ ";
        if (rc != (std::size_t) - 1)
            for (unsigned char c8 : std::string_view{out, rc})
                std::cout << +c8 << ' ';
        std::cout << "]\n";
    }
}

输出

Processing 4 UTF-32 code units: [ 0x7a 0xdf 0x6c34 0x1f34c ]
0x7a converted to [ 0x7a ]
0xdf converted to [ 0xc3 0x9f ]
0x6c34 converted to [ 0xe6 0xb0 0xb4 ]
0x1f34c converted to [ 0xf0 0x9f 0x8d 0x8c ]

[edit] 参见

(C++11)
将窄多字节字符转换为 UTF-32 编码
(函数) [edit]
[虚函数]
将字符串从 InternT 转换为 ExternT,例如在写入文件时
(std::codecvt<InternT,ExternT,StateT> 的虚保护成员函数) [edit]
C 文档 关于 c32rtomb