一生一世学坛

 找回密码
 立即注册
搜索
查看: 3790|回复: 0
打印 上一主题 下一主题

C++ string转utf8

[复制链接]

334

主题

385

帖子

6830

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
6830
跳转到指定楼层
楼主
发表于 2021-6-18 11:03:23 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
  1. 普通sting类型 转UTF-8编码格式字符串
  2. std::string RadarDataController::string_To_UTF8(const std::string & strSrc)
  3. {
  4.     int nwLen = ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);

  5.     wchar_t * pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴
  6.     ZeroMemory(pwBuf, nwLen * 2 + 2);

  7.     ::MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.length(), pwBuf, nwLen);

  8.     int nLen = ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, NULL, NULL, NULL);

  9.     char * pBuf = new char[nLen + 1];
  10.     ZeroMemory(pBuf, nLen + 1);

  11.     ::WideCharToMultiByte(CP_UTF8, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);

  12.     std::string retStr(pBuf);

  13.     delete []pwBuf;
  14.     delete []pBuf;

  15.     pwBuf = NULL;
  16.     pBuf = NULL;

  17.     return retStr;
  18. }
复制代码
  1. UTF-8编码格式字符串  转普通sting类型
  2. {
  3.     int nwLen = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);

  4.     wchar_t * pwBuf = new wchar_t[nwLen + 1];//一定要加1,不然会出现尾巴
  5.     memset(pwBuf, 0, nwLen * 2 + 2);

  6.     MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), pwBuf, nwLen);

  7.     int nLen = WideCharToMultiByte(CP_ACP, 0, pwBuf, -1, NULL, NULL, NULL, NULL);

  8.     char * pBuf = new char[nLen + 1];
  9.     memset(pBuf, 0, nLen + 1);

  10.     WideCharToMultiByte(CP_ACP, 0, pwBuf, nwLen, pBuf, nLen, NULL, NULL);

  11.     std::string retStr = pBuf;

  12.     delete []pBuf;
  13.     delete []pwBuf;

  14.     pBuf = NULL;
  15.     pwBuf = NULL;

  16.     return retStr;

  17. }
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|分享学习  

GMT+8, 2024-5-17 12:42 , Processed in 0.042542 second(s), 6 queries , File On.

声明:本站严禁任何人以任何形式发表违法言论!

本站内容由网友原创或转载,如果侵犯了您的合法权益,请及时联系处理!© 2017 zamxqun@163.com

皖公网安备 34010402700634号

皖ICP备17017002号-1

快速回复 返回顶部 返回列表