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);

Convert to bytes
Returns the byte-string equivalent of wchar or sequence of wide characters represented by its arguments.

If the wstring_convert object was constructed with no explicit shift state value (constructors (1) and (3)), the shift state is reset before the conversion begins.

Parameters

wchar
A single wide character.
wptr
A null-terminated wide character sequence (a wide C-string).
wstr
A string of wide characters.
wide_string is a member type, defined as an alias of basic_string<Elem,char_traits<Elem>,Wide_alloc> (where Elem and Wide_alloc are the second and third template parameters of wstring_convert, respectivelly).
first,last
Pointers to the first and past-the-end wide characters in a sequence. The range converted contains all the wide characters between first and last, without including the wide character pointed by last.

Return value

If successful, the sequence of bytes resulting from the conversion, as a
wide string.
Otherwise, if the wstring_convert object was constructed with an error byte string (constructor (3)), this error string is returned.
Otherwise, range_error is thrown.

byte_string is a member type, defined as an alias of basic_string<char,char_traits<char>,Byte_alloc> (where Byte_alloc is the fourth template parameter of wstring_convert).

The number of characters converted can be accessed with member converted.

Example

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;
}


Output:

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

Data races

The wstring_convert object is modified.
Elements in the sequence pointed by the arguments (if any) are accessed.

Exception safety

Basic guarantee: if an exception is thrown, the object is in a valid state.
It throws an exception of type range_error if the function fails.

See also