加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C++宽字符与普通字符的转换实例详解

发布时间:2020-12-16 05:09:07 所属栏目:百科 来源:网络整理
导读:C++宽字符与普通字符的转换实例详解 把字符串转换成宽字符串, 实例代码: wstring string2Wstring(string sToMatch) { #ifdef _A_WIN int iWLen = MultiByteToWideChar( CP_ACP,sToMatch.c_str(),sToMatch.size(),0 ); // 计算转换后宽字符串的长度。(不包

C++宽字符与普通字符的转换实例详解

把字符串转换成宽字符串,

实例代码:

wstring string2Wstring(string sToMatch) 
{   
#ifdef _A_WIN 
  int iWLen = MultiByteToWideChar( CP_ACP,sToMatch.c_str(),sToMatch.size(),0 ); // 计算转换后宽字符串的长度。(不包含字符串结束符) 
  wchar_t *lpwsz = new wchar_t [iWLen + 1]; 
  MultiByteToWideChar( CP_ACP,lpwsz,iWLen ); // 正式转换。 
  lpwsz[iWLen] = L'/0';  
  wstring wsToMatch(lpwsz); 
  delete []lpwsz; 
#elif _A_LINUX 
  setlocale( LC_CTYPE,"" ); // 很重要,没有这一句,转换会失败。 
  int iWLen = mbstowcs( NULL,sToMatch.length() ); // 计算转换后宽字符串的长度。(不包含字符串结束符) 
  wchar_t *lpwsz = new wchar_t[iWLen + 1]; 
  int i = mbstowcs( lpwsz,sToMatch.length() ); // 转换。(转换后的字符串有结束符) 
  wstring wsToMatch(lpwsz); 
  delete []lpwsz; 
#endif 
  return wsToMatch; 
} 
//把宽字符串转换成字符串,输出使用 
string wstring2string(wstring sToMatch) 
{   
#ifdef _A_WIN 
  string sResult; 
  int iLen = WideCharToMultiByte( CP_ACP,NULL,-1,FALSE ); // 计算转换后字符串的长度。(包含字符串结束符) 
  char *lpsz = new char[iLen]; 
  WideCharToMultiByte( CP_OEMCP,lpsz,iLen,FALSE); // 正式转换。 
  sResult.assign( lpsz,iLen - 1 ); // 对string对象进行赋值。 
  delete []lpsz; 
#elif _A_LINUX 
  int iLen = wcstombs( NULL,0 ); // 计算转换后字符串的长度。(不包含字符串结束符) 
  char *lpsz = new char[iLen + 1]; 
  int i = wcstombs( lpsz,iLen ); // 转换。(没有结束符) 
  lpsz[iLen] = '/0'; 
  string sResult(lpsz); 
  delete []lpsz; 
#endif 
  return sResult; 
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读