string UTF8ToGBK(const string &utf8)
{
int length1 = MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,utf8.c_str(),utf8.length(),NULL,0);
if(length1 > 0)
{
WCHAR *wbuf = new WCHAR[length1 * 2 + 2];
memset(wbuf,0,length1 * 2 + 2);
int length2 = MultiByteToWideChar(CP_UTF8,0,utf8.c_str(),utf8.length(),wbuf,length1);
if(length2 > 0)
{
length1 = WideCharToMultiByte(CP_ACP,0,buf,length2,NULL,0,NULL,NULL);
if(length1 > 0)
{
char *buf = new char[length1 + 1];
memset(buf,0,length1 + 1);
length2 = WideCharToMultiByte(CP_ACP,0,wbuf,length2,buf,length1,NULL,NULL);
if(length2 > 0)
{
string gbk(buf);
delete []wbuf;
delete []buf;
return gbk;
}
else
{
delete []wbuf;
delete []buf;
return utf8;
}
}
}
else
{
delete []wbuf;
return utf8;
}
}
return utf8;
}
测试代码:
string ss = "中文状态";//这个地方一定要保存为UTF-8 with signature,不然会有new line in constant错误
string str = UTF8ToGBK(ss);
cout<<str;//中文状态