std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>::to_bytes
来自cppreference.com
| 在标头 <locale> 定义
|
||
| |
(1) | |
| |
(2) | |
| |
(3) | |
| |
(4) | |
用 cvtptr 指向的刻面将宽序列转换成字节字符串。
1) 宽序列只包含单个元素
byte。2) 宽序列是从
ptr 开始的空终止序列。3) 宽序列是
str 包含的序列。4) 宽序列是范围
[first, last)。在转换开始前,如果 *this 不是以构造函数重载 (3) 构造的,那么会将 cvtstate 设为它的默认值(初始转换状态)。
成功转换的输入元素数量会存储到 cvtcount 中。
返回值
如果转换成功,那么返回转换结果。否则,如果 *this 是以构造函数重载 (4) 构造的,那么就会返回 byte_err_string。
异常
如果转换失败,并且 *this 不是以构造函数重载 (4) 构造的,那么就会抛出 std::range_error。
示例
运行此代码
#include <codecvt>
#include <iomanip>
#include <iostream>
#include <locale>
#include <string>
// 输出用的工具函数
void hex_print(const std::string& s)
{
std::cout << std::hex << std::setfill('0');
for(unsigned char c : s)
std::cout << std::setw(2) << static_cast<int>(c) << ' ';
std::cout << std::dec << '\n';
}
int main()
{
// 宽字符数据
std::wstring wstr = L"z\u00df\u6c34\U0001f34c"; // 或 L"zß水🍌"
// 宽到 UTF-8
std::wstring_convert<std::codecvt_utf8<wchar_t>> conv1;
std::string u8str = conv1.to_bytes(wstr);
std::cout << "UTF-8 转换产生了 " << u8str.size() << " 个字节:\n";
hex_print(u8str);
// 宽到 UTF-16le
std::wstring_convert<std::codecvt_utf16<wchar_t, 0x10ffff, std::little_endian>> conv2;
std::string u16str = conv2.to_bytes(wstr);
std::cout << "UTF-16le 转换产生了 " << u16str.size() << " 个字节:\n";
hex_print(u16str);
}
输出:
UTF-8 转换产生了 10 个字节:
7a c3 9f e6 b0 b4 f0 9f 8d 8c
UTF-16le 转换产生了 10 个字节:
7a 00 df 00 34 6c 3c d8 4c df
参阅
| 转换字节字符串为宽字符串 (公开成员函数) | |
| 给定状态,转换宽字符串为窄多字节字符串 (函数) | |
[虚] |
将字符串从 InternT 转换到 ExternT,例如在写入文件时 ( std::codecvt<InternT,ExternT,StateT> 的虚受保护成员函数) |