Vc++中UTF-8、ANSI 互转
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2022-09-20 19:17:12
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
UTF8 <=> Ansi
std::string Utf8ToAnsi(const char* szUtf8) { const int WLength = MultiByteToWideChar(CP_UTF8, 0, szUtf8, -1, nullptr, NULL); const auto pszW = new WCHAR[WLength + 1]{ 0 }; MultiByteToWideChar(CP_UTF8, 0, szUtf8, -1, pszW, WLength); const int ALength = WideCharToMultiByte(CP_ACP, 0, pszW, -1, nullptr, 0, nullptr, nullptr); const auto pszA = new char[ALength + 1]{ 0 }; WideCharToMultiByte(CP_ACP, 0, pszW, -1, pszA, ALength, nullptr, nullptr); std::string retStr = pszA; delete[] pszW; delete[] pszA; return retStr; }
ANSI <=> UTF-8
std::string AnsiToUtf8(const char* szAnsi) { const int WLength = MultiByteToWideChar(CP_ACP, 0, szAnsi, -1, nullptr, 0); const auto pszW = new WCHAR[WLength + 1]{ 0 }; MultiByteToWideChar(CP_ACP, 0, szAnsi, -1, pszW, WLength); const int ALength = WideCharToMultiByte(CP_UTF8, 0, pszW, -1, nullptr, 0, nullptr, nullptr); const auto pszA = new char[ALength + 1]{ 0 }; WideCharToMultiByte(CP_UTF8, 0, pszW, -1, pszA, ALength, nullptr, nullptr); std::string retStr(pszA); delete[] pszW; delete[] pszA; return retStr; }