Original Post
I'm doing my best to be Unicode compliant, but a lot of libaries still expect ANSI/UTF-8 and I'm using std::wstring internally. Question is, what's the best way to widen and narrow strings? This is the code I'm using currently: The widen function works beautifully, but the narrow function basically just prays to God that the string is in UTF-8 and therefore the typecast will output meaningful data instead of gibberish (not to mention overflow problems). So if anyone knows a better way to do either of these tasks, I'd love to learn it!
std::wstring widen(const std::string& str)
{
std::wstring ret;
ret.reserve(str.size());
for(std::string::const_iterator iter = str.begin(); iter != str.end(); ++iter)
ret += std::use_facet<std::ctype<wchar_t> >(std::wcout.getloc()).widen(*iter);
return ret;
}
std::string narrow(const std::wstring& str)
{
// EVIL HACK
std::string ret;
ret.reserve(str.size());
for(std::wstring::const_iterator iter = str.begin(); iter != str.end(); ++iter)
ret += static_cast<char>(*iter);
return ret;
}