std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>::from_bytes
来自 cppreference.cn
< 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
指向的 facet 将字节序列转换为宽字符串。
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"; // or u8"zß水𝄋" // or "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b"; // the UTF-8 / UTF-16 standard conversion facet std::u16string utf16 = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.from_bytes(utf8.data()); std::cout << "UTF-16 conversion produced " << utf16.size() << " code units: " << std::showbase; for (char16_t c : utf16) std::cout << std::hex << static_cast<std::uint16_t>(c) << ' '; // the UTF-8 / UTF-32 standard conversion facet std::u32string utf32 = std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t>{}.from_bytes(utf8); std::cout << "\nUTF-32 conversion produced " << std::dec << utf32.size() << " code units: "; for (char32_t c : utf32) std::cout << std::hex << static_cast<std::uint32_t>(c) << ' '; std::cout << '\n'; }
输出
UTF-16 conversion produced 5 code units: 0x7a 0xdf 0x6c34 0xd834 0xdd0b UTF-32 conversion produced 4 code units: 0x7a 0xdf 0x6c34 0x1d10b
[编辑] 参见
将宽字符串转换为字节字符串 (公共成员函数) | |
给定状态,将窄多字节字符串转换为宽字符串 (函数) | |
[虚函数] |
将字符串从 ExternT 转换为 InternT,例如从文件读取时 (std::codecvt<InternT,ExternT,StateT> 的虚保护成员函数) |