命名空间
变体
操作

std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>::to_bytes

来自 cppreference.cn
 
 
 
 
 
定义于头文件 <locale>
byte_string to_bytes( Elem wchar );
(1)
byte_string to_bytes( const Elem* wptr );
(2)
byte_string to_bytes( const wide_string& wstr );
(3)
byte_string to_bytes( const Elem* first, const Elem* last );
(4)

使用 cvtptr 指向的 facet 将宽序列转换为字节字符串。

1) 宽序列仅由一个元素 byte 组成。
2) 宽序列是以 ptr 开头的空字符结尾序列。
3) 宽序列是 str 中包含的序列。
4) 宽序列是范围 [firstlast)

在转换开始之前,如果 *this 不是用构造函数重载 (3) 构造的,则 cvtstate 将被设置为其默认值(初始转换状态)。

成功转换的输入元素数量将存储在 cvtcount 中。

目录

[编辑] 返回值

如果转换成功,则返回转换结果。否则,如果 *this 是用构造函数重载 (4) 构造的,则返回 byte_err_string

[编辑] 异常

如果转换失败且 *this 不是用构造函数重载 (4) 构造的,则抛出 std::range_error

[编辑] 示例

#include <codecvt>
#include <iomanip>
#include <iostream>
#include <locale>
#include <string>
 
// utility function for output
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()
{
    // wide character data
    std::wstring wstr = L"z\u00df\u6c34\U0001f34c"; // or L"zß水🍌"
 
    // wide to UTF-8
    std::wstring_convert<std::codecvt_utf8<wchar_t>> conv1;
    std::string u8str = conv1.to_bytes(wstr);
    std::cout << "UTF-8 conversion produced " << u8str.size() << " bytes:\n";
    hex_print(u8str);
 
    // wide to 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 conversion produced " << u16str.size() << " bytes:\n";
    hex_print(u16str);
}

输出

UTF-8 conversion produced 10 bytes:
7a c3 9f e6 b0 b4 f0 9f 8d 8c 
UTF-16le conversion produced 10 bytes:
7a 00 df 00 34 6c 3c d8 4c df

[编辑] 参见

将字节字符串转换为宽字符串
(公共成员函数) [编辑]
在给定状态下,将宽字符串转换为窄多字节字符字符串
(函数) [编辑]
[虚函数]
将字符串从 InternT 转换为 ExternT,例如写入文件时
(std::codecvt<InternT,ExternT,StateT> 的虚保护成员函数) [编辑]