Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

There is no method std::to_u16string(...). Obviously static_cast doesn't seem the most appropiate way to make such conversion.

For the opposite conversion, from string to int, a converter may be defined using the function std::stoi(), but from int to u16string it's not working.

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 it doesn't work.

Is there a way to carry out this conversion directly, or there must be some intermediate conversions?

like image 296
J. A. Corbal Avatar asked Dec 10 '15 20:12

J. A. Corbal


1 Answers

You could 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

like image 140
101010 Avatar answered Sep 27 '22 22:09

101010