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

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
);

  


/**************************************************************************
                  原文来自博客园——Submarinex的博客: www.cnblogs.com/submarinex/               
  *************************************************************************/

原文地址:https://www.cnblogs.com/submarinex/p/2539044.html