C++ 字符串UTF8與GBK轉化。本站提示廣大學習愛好者:(C++ 字符串UTF8與GBK轉化)文章只能為提供參考,不一定能成為您想要的結果。以下是C++ 字符串UTF8與GBK轉化正文
第一次寫博客,有時分在任務中遇到解析XML文件,節點屬性值為中文的狀況,需求轉換編碼,VC默許是的是GB2312,遇到中文就呈現亂碼,上面是UTF-8和GBK2312的相互轉換,有弄巧成拙的中央,希望各位大神指出:
#include "windows.h"
// UTF-8轉為GBK2312 [1/18/2017/shike]
std::string UtfToGbk(const char* utf8)
{
int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len+1];
memset(wstr, 0, len+1);
MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len);
len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL);
char* str = new char[len+1];
memset(str, 0, len+1);
WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL);
if(wstr) delete[] wstr;
return str;
}
//GBK轉化為UTF8格式
void ConvertGBKToUtf8(CString &strGBK)
{
int len=MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -1, NULL,0);
wchar_t * wszUtf8 = new wchar_t [len];
memset(wszUtf8, 0, len);
MultiByteToWideChar(CP_ACP, 0, (LPCTSTR)strGBK, -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);
strGBK = szUtf8;
delete[] szUtf8;
delete[] wszUtf8;
}