public member function
<locale>

std::wstring_convert::to_bytes

byte_string to_bytes (Elem wchar);byte_string to_bytes (const Elem* wptr);byte_string to_bytes (const wide_string& wstr);byte_string to_bytes (const Elem* first, const Elem* last);
轉換為位元組
返回由其引數表示的wchar寬字元序列位元組字串等效項。

如果wstring_convert物件在沒有顯式移位狀態值的情況下構造(建構函式 (1) 和 (3)),則在轉換開始前會重置移位狀態

引數

wchar
單個寬字元。
wptr
一個以 null 結尾的寬字元序列(一個寬 C 字串)。
wstr
寬字元字串。
wide_string 是一個成員型別,定義為 basic_string<Elem,char_traits<Elem>,Wide_alloc> 的別名(其中 ElemWide_alloc 分別是 wstring_convert 的第二個和第三個模板引數)。
first,last
指向序列中第一個尾部之後的寬字元的指標。轉換的範圍包含 firstlast 之間的所有寬字元,不包括 last 指向的寬字元

返回值

如果成功,轉換產生的位元組序列,作為
寬字串.
否則,如果wstring_convert物件是用錯誤位元組字串構造的(建構函式 (3)),則返回此錯誤字串。
否則,將丟擲range_error

byte_string 是一個成員型別,定義為 basic_string<char,char_traits<char>,Byte_alloc> 的別名(其中 Byte_allocwstring_convert 的第四個模板引數)。

轉換的字元數可以透過成員 converted 訪問。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// converting from UTF-16 to UTF-8
#include <iostream>       // std::cout, std::hex
#include <string>         // std::string, std::u16string
#include <locale>         // std::wstring_convert
#include <codecvt>        // std::codecvt_utf8_utf16

int main ()
{
  std::u16string str16 (u"\u3084\u3042");  // UTF-16 for YAA (やあ)

  std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> cv;

  std::string str8 = cv.to_bytes(str16);

  std::cout << std::hex;

  std::cout << "UTF-8: ";
  for (char c : str8)
    std::cout << '[' << int(static_cast<unsigned char>(c)) << ']';
  std::cout << '\n';

  return 0;
}


輸出

UTF-8: [e3][82][84][e3][81][82]


資料競爭

wstring_convert 物件將被修改。
將訪問引數指向的序列中的元素(如果存在)。

異常安全

基本保證:如果丟擲異常,物件處於有效狀態。
如果函式失敗,則丟擲型別為 range_error 的異常。

另見