How to convert an integer to std :: u16string (C ++ 11)?

There is no method std::to_u16string(...). Obviously, this static_castdoes not seem to be the most appropriate way to do such a transformation.

For the opposite conversion, from stringto int, the converter can be determined using a function std::stoi(), but from intto u16stringit does not work.

I tried the following:

int i = 1234;
std::u16string s;

std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
s = convert.from_bytes(std::to_string(i));

std::cout << s.str() << "  (" << s.length() << ")" << std::endl;

I also tried to do this:

typedef std::basic_stringstream<char16_t> u16ss;
u16ss ss;
ss << 1234;
std::u16string s = ss.str();

but that will not work.

Is there a way to do this conversion directly or should there be some intermediate conversions?

+4
source share
1 answer

You can try the following:

std::u16string to_u16string(int const &i) {
  std::wstring_convert<std::codecvt_utf8_utf16<char16_t, 0x10ffff, std::little_endian>, char16_t> conv;
  return conv.from_bytes(std::to_string(i));
}

Live demo

+3

Source: https://habr.com/ru/post/1619407/


All Articles