将string和wstring互转

  1. #include<string>   
  2. using namespace std;   
  3.   
  4. //将string转换成wstring   
  5. wstring string2wstring(string str)   
  6. {   
  7.     wstring result;   
  8.     //获取缓冲区大小,并申请空间,缓冲区大小按字符计算   
  9.     int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);   
  10.     TCHAR* buffer = new TCHAR[len + 1];   
  11.     //多字节编码转换成宽字节编码   
  12.     MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);   
  13.     buffer[len] = '/0';             //添加字符串结尾   
  14.     //删除缓冲区并返回值   
  15.     result.append(buffer);   
  16.     delete[] buffer;   
  17.     return result;   
  18. }   
  19.   
  20. //将wstring转换成string   
  21. string wstring2string(wstring wstr)   
  22. {   
  23.     string result;   
  24.     //获取缓冲区大小,并申请空间,缓冲区大小事按字节计算的   
  25.     int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);   
  26.     char* buffer = new char[len + 1];   
  27.     //宽字节编码转换成多字节编码   
  28.     WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);   
  29.     buffer[len] = '/0';   
  30.     //删除缓冲区并返回值   
  31.     result.append(buffer);   
  32.     delete[] buffer;   
  33.     return result;   
  34. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值