Mikhail Lucas
Mikhail Lucas

Reputation: 11

Convert to string from an array of characters

I would like to convert an array of characters to a wide string like this

std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring ws=converter.from_bytes({99,108,105,235,110,116}).

But this doesn't work.

`235` is an invalid narrowing conversion from int to char:constant character doesn't fit in destination type.

Upvotes: 0

Views: 93

Answers (1)

T.C.
T.C.

Reputation: 137394

The only arguably viable overload of from_bytes for your code is the version taking a const byte_string&. You aren't using a custom allocator, so byte_string is std::basic_string<char, std::char_traits<char>, std::allocator<char>>, a.k.a. std::string.

std::string has an initalizer_list<char> constructor; however, char on your platform is signed, and cannot represent the value 235, making the implicit conversion from 235 to char a narrowing conversion, which is not allowed at the top level of a braced initializer list.

Use char(235) instead to explicitly convert it to a char.

Upvotes: 1

Related Questions