名稱空間
變體
操作

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

來自 cppreference.com
 
 
 
 
 
定義於標頭檔案 <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> 的虛保護成員函式) [編輯]