utf8转gbk

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;//中文状态

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奥特曼VS怪兽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值