vs中直接顯示utf8數據,會是亂碼,vs中的默認編碼格式是gbk,所以可以將utf8轉換爲gbk
下面是轉換:
std::string utf8ToGBK(const std::string &strUtf8)
{
int len = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, NULL, 0);
wchar_t * wszGBK = new wchar_t[len + 1];
memset(wszGBK, 0, len + 1);
MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wszGBK, len);
len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
char *szGBK = new char[len + 1];
memset(szGBK, 0, len + 1);
WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL);
std::string strGBK(szGBK);
delete[] szGBK;
delete[] wszGBK;
return strGBK;
}
同時,vs中的編碼格式是gbk,所以在網絡中一般都是使用utf8的編碼格式來進行傳輸的,所以需要gbk轉utf8格式
下面是轉換:
std::string gbkToUtf8(const std::string &strGBK)
{
int len = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
wchar_t * wszUtf8 = new wchar_t[len];
memset(wszUtf8, 0, len);
MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, wszUtf8, len);
len = WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, NULL, 0, NULL, NULL);
char *szUtf8 = new char[len + 1];
memset(szUtf8, 0, len + 1);
WideCharToMultiByte(CP_UTF8, 0, wszUtf8, -1, szUtf8, len, NULL, NULL);
std::string strUTF8(szUtf8);
delete[] szUtf8;
delete[] wszUtf8;
return strUTF8;
}