Conversion Between std::string and std::wstring

Started by
1 comment, last by maxest 7 years, 7 months ago

http://wojtsterna.blogspot.com/

Enjoy :)

Advertisement

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 :)

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

This topic is closed to new replies.

Advertisement