std::wstring_convert<Codecvt,Elem,Wide_alloc,Byte_alloc>:: to_bytes
|
定义于头文件
<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 将宽序列转换为字节字符串。
[
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
另请参阅
|
将字节字符串转换为宽字符串
(公开成员函数) |
|
|
在给定状态的情况下将宽字符串转换为窄多字节字符串
(函数) |
|
|
[virtual]
|
将字符串从
InternT
转换为
ExternT
,例如写入文件时
(
std::codecvt<InternT,ExternT,StateT>
的虚受保护成员函数)
|