C++ <codecvt> utf8 string to utf16

1.5k views Asked by At

I'd like to convert a string to a utf-16 wstring. I wrote the following code :

std::string str = "aé"; // a test string with a French character

using cvt_type = std::codecvt_utf8_utf16<wchar_t>;
std::wstring_convert<cvt_type> converter;

std::wstring wstr = converter.from_bytes(str); // exception: std::range_error

The example above works fine with strings containing unicode (for instance std::string str="\u0061\u00e9") or strings without special characters. But my first example doesn't work.

I get the following exception : Microsoft C++ exception: std::range_error at memory location 0x00A9E7E4 The program stops there : converter.from_bytes(str);

When I add the line str[1]=130; // é everything works fine, so I guess that signed chars are the reason for the issue. I need to use a string of signed chars because I want to send the data over tcp sockets.

How to perform the conversion, so that I can send my data using sockets?

Thanks in advance.

0

There are 0 answers