1 std::wstring ANSIToUnicode(const std::string& str) 2 { 3 int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0); 4 std::vector<wchar_t> unicode(len); 5 MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, &unicode[0], len); 6 return std::wstring(&unicode[0]); 7 } 8 9 std::string UnicodeToANSI(const std::wstring& str) 10 { 11 int len = WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, NULL, 0, NULL, NULL); 12 std::vector<char> utf8(len); 13 WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, &utf8[0], len, NULL, NULL); 14 15 return std::string(&utf8[0]); 16 } 17 18 std::wstring UTF8ToUnicode(const std::string& str) 19 { 20 int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0); 21 std::vector<wchar_t> unicode(len); 22 MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &unicode[0], len); 23 return std::wstring(&unicode[0]); 24 } 25 26 std::string UnicodeToUTF8(const std::wstring& str) 27 { 28 int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, NULL, 0, NULL, NULL); 29 std::vector<char> utf8(len); 30 WideCharToMultiByte(CP_UTF8, 0, str.c_str(), -1, &utf8[0], len, NULL, NULL); 31 32 return std::string(&utf8[0]); 33 } 34 35 std::string ANSIToUTF8(const std::string& str) 36 { 37 return UnicodeToUTF8(ANSIToUnicode(str)); 38 } 39 40 std::string UTF8ToANSI(const std::string str) 41 { 42 return UnicodeToANSI(UTF8ToUnicode(str)); 43 }
原文:http://www.cnblogs.com/dev-ptr/p/6274562.html