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

来自cppreference.com
 
 
 
 
在标头 <locale> 定义
wide_string from_bytes( char byte );
(1)
wide_string from_bytes( const char* ptr );
(2)
wide_string from_bytes( const byte_string& str );
(3)
wide_string from_bytes( const char* first, const char* last );
(4)

用构造中时提供的 codecvt 刻面,进行多字节到宽转换。

1) 转换 bytewide_string,如同它是长为 1 的字符串。
2) 转换始于 ptr 所指向字符的空终止多字节字符序列为 wide_string
3) 转换窄字符串 strwide_string
4) 转换窄多字节字符序列 [firstlast)wide_string

所有情况下,转换以初始迁移状态起始,除非提供了非初始起始状态给此 wstring_convert 的构造函数。记忆转换的字符数和转换状态的终值,并且能以 state()converted() 访问它们。

返回值

含有多字节到宽转换结果的 wide_string 对象。若转换失败,且有用户提供的宽错误字符串提供给此 wstring_convert 的构造函数,则返回该宽错误字符串。

异常

若此 wstring_convert 不以用户提供的宽错误字符串构造,则在转换失败时抛出 std::range_error

示例

#include <codecvt>
#include <cstdint>
#include <iostream>
#include <locale>
#include <string>
 
int main()
{
    std::string utf8 = "z\u00df\u6c34\U0001d10b"; // 或 u8"zß水𝄋"
                 // 或 "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b";
 
    // UTF-8 / UTF-16 标准转换刻面
    std::u16string utf16 = std::wstring_convert<
        std::codecvt_utf8_utf16<char16_t>, char16_t>{}.from_bytes(utf8.data());
    std::cout << "UTF-16 转换产生了 " << utf16.size()
              << " 个代码单元: " << std::showbase;
    for (char16_t c : utf16)
        std::cout << std::hex << static_cast<std::uint16_t>(c) << ' ';
 
    // UTF-8 / UTF-32 标准转换刻面
    std::u32string utf32 = std::wstring_convert<
        std::codecvt_utf8<char32_t>, char32_t>{}.from_bytes(utf8);
    std::cout << "\nUTF-32 转换产生了 " << std::dec
              << utf32.size() << " 个代码单元: ";
    for (char32_t c : utf32)
        std::cout << std::hex << static_cast<std::uint32_t>(c) << ' ';
    std::cout << '\n';
}

输出:

UTF-16 转换产生了 5 个代码单元: 0x7a 0xdf 0x6c34 0xd834 0xdd0b
UTF-32 转换产生了 4 个代码单元: 0x7a 0xdf 0x6c34 0x1d10b

参阅

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