//---------------编码gbk 转utf-8解决中文乱码-------------------
string GBKToUTF8(std::string& strGBK){
string strOutUTF8 = "";
wchar_t * str1;
int n = MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, NULL, 0);
str1 = new WCHAR[n];
MultiByteToWideChar(CP_ACP, 0, strGBK.c_str(), -1, str1, n);
n = WideCharToMultiByte(CP_UTF8, 0, str1, -1, NULL, 0, NULL, NULL);
char * str2 = new char[n];
WideCharToMultiByte(CP_UTF8, 0, str1, -1, str2, n, NULL, NULL);
strOutUTF8 = str2;
delete[]str1;
str1 = NULL;
delete[]str2;
str2 = NULL;
return strOutUTF8;
}
//---------------编码utf-8转gbk 解决中文乱码-------------------
void CGps_RecordDlg::ConvertUtf8ToGBK(CString& strUtf8)
{
int len=MultiByteToWideChar(CP_UTF8, 0, (LPSTR)(LPCTSTR)strUtf8, -1, NULL,0);
unsigned short * wszGBK = new unsigned short[len+1];
memset(wszGBK, 0, len * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, (LPSTR)(LPCTSTR)strUtf8, -1, (LPWSTR)wszGBK, len);
len = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)wszGBK, -1, NULL, 0, NULL, NULL);
char *szGBK=new char[len + 1];
memset(szGBK, 0, len + 1);
WideCharToMultiByte (CP_ACP, 0, (LPCWSTR)wszGBK, -1, szGBK, len, NULL,NULL);
strUtf8 = szGBK;
delete[] szGBK;
delete[] wszGBK;
}

本文详细介绍了如何使用C++实现GBK到UTF-8和UTF-8到GBK的编码转换,有效解决中文乱码问题。通过多字节到宽字符的转换,再将宽字符转换为指定编码的字符串,实现了跨编码的文本数据处理。

被折叠的 条评论
为什么被折叠?



