VC UTF-8與中文(GB2312)相互轉換
#include <string>
using namespace std;
/************************************************************************/
/* 將gb2312編碼轉為UTF-8字元 */
/************************************************************************/
std::string GBToUTF8(const char*);
/************************************************************************/
/* 將UTF-8編碼轉為gb2312字元 */
/************************************************************************/
std::string UTF8ToGB(const char*);
std::string GBToUTF8(const char* str)
{
std::string result;
WCHAR *strSrc;
//TCHAR *szRes;
//獲得臨時變數的大小
int i = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0);
strSrc = new WCHAR[i+1];
MultiByteToWideChar(CP_ACP, 0, str, -1, strSrc, i);
//獲得臨時變數的大小
//i = WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, NULL, 0, NULL, NULL);
//szRes = new TCHAR[i+1];
//int j=WideCharToMultiByte(CP_UTF8, 0, strSrc, -1, szRes, i, NULL, NULL);
result = szSrc;
delete []strSrc;
//delete []szRes;
return result;
}
std::string UTF8ToGB(const char* str)
{
std::string result;
WCHAR *strSrc;
//TCHAR *szRes;
//獲得臨時變數的大小
int i = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
strSrc = new WCHAR[i+1];
MultiByteToWideChar(CP_UTF8, 0, str, -1, strSrc, i);
//獲得臨時變數的大小
//i = WideCharToMultiByte(CP_ACP, 0, strSrc, -1, NULL, 0, NULL, NULL);
//szRes = new TCHAR[i+1];
//WideCharToMultiByte(CP_ACP, 0, strSrc, -1, szRes, i, NULL, NULL);
result = szSrc;
delete []strSrc;
//delete []szRes;
return result;
}
忘記在哪拿來的了,以後找到了再寫原帖,如果有發現的,可以告知,謝謝!