#include <iostream> #include <codecvt> std::string convertToUtf8(const std::wstring& str) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> converter; return converter.to_bytes(str); } std::wstring convertToUtf16(const std::string& str) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> converter; return converter.from_bytes(str); } int main(int argc, char** argv) { std::wstring wstr = L"我是中国人"; std::string str = convertToUtf8(wstr); std::cout << str << std::endl; getchar(); return 0; }
仅仅这么处理会导致乱码,因为控制台默认是ASCI编码,显示UTF8的编码会乱码。此时需要把UTF8转ASCI,然后在控制台显示
增加转码函数
#include <iostream> #include <codecvt> #include <Windows.h> std::string convertToUtf8(const std::wstring& str) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> converter; return converter.to_bytes(str); } std::wstring convertToUtf16(const std::string& str) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> converter; return converter.from_bytes(str); } std::wstring Utf8ToUnicode(const std::string& strUTF8) { int len = MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, NULL, 0); if (len == 0) { return L""; } wchar_t *pRes = new wchar_t[len]; if (pRes == NULL) { return L""; } MultiByteToWideChar(CP_UTF8, 0, strUTF8.c_str(), -1, pRes, len); pRes[len - 1] = L'\0'; std::wstring result = pRes; delete[] pRes; return result; } std::string Utf8ToAnsi(const std::string& utf8) { std::wstring wstrTemp = Utf8ToUnicode(utf8); LPCWCH ptr = wstrTemp.c_str(); int size = WideCharToMultiByte(CP_ACP, 0, ptr, -1, NULL, 0, NULL, NULL); std::string strRet(size - 1, 0); int len = WideCharToMultiByte(CP_ACP, 0, ptr, -1, (LPSTR)strRet.c_str(), size, NULL, NULL); return strRet; } int main(int argc, char** argv) { std::wstring wstr = L"我是中国人"; std::string str = Utf8ToAnsi(convertToUtf8(wstr)); std::cout << str << std::endl; getchar(); return 0; }