宽字符字符串和多字节字符串之间转换

MFC中,使用Edit控件显示中文遇到乱码。自己写了两个函数进行转化

 1 // CString转换成string
 2 string CDictDlg::CString2string(CString &str)
 3 {
 4     char *pCh = new char[MY_EDIT_TEXT_LENG];
 5     // W(2B) -> A(B)
 6     WideCharToMultiByte(CP_ACP, 0, str.GetBuffer(), -1, pCh, str.GetLength() * 2, NULL, NULL);
 7     pCh[str.GetLength() * 2] = 0;
 8     string sRet(pCh);
 9     delete pCh;
10 
11     return sRet;
12 }
13 
14 // string转换成wchar_t *类型
15 wchar_t *CDictDlg::string2pwc(string &str)
16 {
17     wchar_t *pwRet = new wchar_t[MY_EDIT_CONTRL_LENG];
18     const char *pcCh(str.c_str());
19     int cchWineChar = MultiByteToWideChar(CP_ACP, 0, pcCh, -1, pwRet, 0);
20     MultiByteToWideChar(CP_ACP, 0, pcCh, -1, pwRet, cchWineChar);
21 
22     return pwRet;
23 }

参考MSDN

WideCharToMultiByte()

int WideCharToMultiByte(
  __in       UINT CodePage,
  __in       DWORD dwFlags,
  __in       LPCWSTR lpWideCharStr,
  __in       int cchWideChar,
  __out_opt  LPSTR lpMultiByteStr,
  __in       int cbMultiByte,
  __in_opt   LPCSTR lpDefaultChar,
  __out_opt  LPBOOL lpUsedDefaultChar
);

 MultiByteToWideChar()

int MultiByteToWideChar(
  __in       UINT CodePage,
  __in       DWORD dwFlags,
  __in       LPCSTR lpMultiByteStr,
  __in       int cbMultiByte,
  __out_opt  LPWSTR lpWideCharStr,
  __in       int cchWideChar
);

  

转载于:https://www.cnblogs.com/submarinex/archive/2012/06/06/2539044.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值