Convert vector<wchar_t> to string c++

183 Views Asked by At

I'm trying to convert a vector<wchar_t> to string (and then print it).

std::string(vector_.begin(), vector_.end());

This code works fine, except äöü ÄÖÜ ß. They will be converted to:

���

I also tried converting to wstring and printing with wcout, but I got the same issue.

Thanks in advance!

1

There are 1 best solutions below

0
Liam K. On BEST ANSWER

My Solution:

First I convert my vector<wchar_t> to an utf16string like this:

std::u16string(buffer_.begin(), buffer_.end());

Then I use this function, I found somewhere on here:

std::string IO::Interface::UTF16_To_UTF8(std::u16string const& str) {
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t, 0x10ffff,
        std::codecvt_mode::little_endian>, char16_t> cnv;
    std::string utf8 = cnv.to_bytes(str);
    if(cnv.converted() < str.size())
        throw std::runtime_error("incomplete conversion");
    return utf8;
}

I did not write the conversion function, but it works just as expected. With this I can successfully convert a vector<wchar_t> to string