Unicode wchar_t -> char

I have to deal with std::wstring encoded in unicode. I need to be able to convert is to std::string (wchar_t -> char). So far, I've tried std::wstring_convert<std::codecvt_utf8<wchar_t> > but it throws a range error indicating that the conversion "failed" (whatever that's supposed to mean).

I have been at this for over a day now and I havn't been able to find anything on it. I've only found that this is supposed to work, but obviously does not. "failed" is extremely cryptic, and doesn't tell me anything, so I don't know what to do here.

Is there anyone who can show me how to convert Unicode-encoded std::wstrings to a plain std::string?


I figured it out... For my test cases, I was generating random wstrings with wchar_ts that had values between 0, and std::numeric_limits<wchar_t>::max(), and apparently, once I limited the values to a max of 0xfff it worked.

Now I have another question: is there a place I can find the max/min supported unicode characters? Or maybe you know a better why to convert unicode wstrings -> strings that doesn't blow up when given a value "out of range"?

The big problem is that I can enter values far greater than wchar_t in my text box, so this is a problem I need to solve. (in linux, ctrl+shift+U would allow me to enter any number I want, thus screwing up things...)

Thanks!
Last edited on
Works for me:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <codecvt>

int main(){
    std::wstring reg_string = L"\x0032\x0030\x0030\x0036\x002E\x0030\x0035\x002E"
        L"\x0031\x0034\x0020\x685C\x0020\x002D\x0053\x0041\x004B\x0055\x0052\x0041"
        L"\x002D\x0020\x7D05\x97FF\x697C\x95A3\x0020\x0053\x0061\x006D\x0070\x006C"
        L"\x0065\x0020\x0043\x0044\x0020\x0028\x6771\x65B9\x30A2\x30EC\x30F3\x30B8"
        L"\x30FB\x8A66\x8074\x76E4\x0029";
    std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> conv{};
    auto b = conv.to_bytes(reg_string);
    auto c = conv.from_bytes(b);
    if (c != reg_string)
        std::cout<< "conversion fails!"<< std::endl;
    else
        std::cout<< "Conversion succeeded!"<< std::endl;
}
Topic archived. No new replies allowed.