Skip to main content
GameDev.net gamedev.net
🔒 Locked

Conversion Between std::string and std::wstring

Started by maxest Sep 14, 2016 at 10:27 PM 1 replies 1.5k views
kolrabi
kolrabi

No, you are doing it wrong. While your code appears to be working, it will only do so when there is a guarantee the string only contains ISO-8859-1 characters. Directory names can contain almost any character (even outside the range of what a wchar_t might be able to represent). You are also mistaken in the += operator of strings/wstrings automatically convert the characters, you are just casting them before handing them to it.

I don't blame you, this stuff is hard. You need to keep track of the encoding of each string and properly convert between them. A simple cast is not enough. The cast from char to wchar_t is fine (if ISO-8859-1), but the cast from wchar_t to char will throw away the upper bits of the character, potentially garbling your text.

Have a look at mbsrtowcs/wcsrtombs. In C++11 they also added codecvt to convert between encodings.

blah :)
maxest
maxest

Thanks for the explanation. I've edited the note to be a bit less wrong :).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.