std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>::from_bytes
来自cppreference.com
< cpp | locale | wstring convert
在标头 <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) | |
用 cvtptr
指向的刻面将字节序列转换成宽字符串。
1) 字节序列只包含单个元素 byte。
2) 字节序列是从 ptr 开始的空终止序列。
3) 字节序列是 str 包含的序列。
4) 字节序列是范围
[
first,
last)
。在转换开始前,如果 *this 不是以构造函数重载 (3) 构造的,那么会将 cvtstate
设为它的默认值(初始转换状态)。
成功转换的输入元素数量会存储到 cvtcount
中。
返回值
如果转换成功,那么返回转换结果。否则,如果 *this 是以构造函数重载 (4) 构造的,那么就会返回 wide_err_string
。
异常
如果转换失败,并且 *this 不是以构造函数重载 (4) 构造的,那么就会抛出 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> 的虚受保护成员函数) |