CString中存储的字符的数据类型为wchar_t类型。
一、CString转换为char *
(1)方法一:使用wcstombs()
- #include <iostream>
- using namespace std;
- #include <atlstr.h>
-
- int main()
- {
- CString str = L"liuxijiao计算机网络";
- wchar_t *pWChar = str.GetBuffer();
- str.ReleaseBuffer();
-
- int nLen = str.GetLength();
- char *pChar = new char[nLen * 2 + 1];
- memset(pChar, 0, nLen * 2 + 1);
- int rtnVal = (int)wcstombs(pChar, pWChar, nLen * 2 + 1);
-
- cout<<pChar<<endl;
-
- delete[] pChar;
- return 0;
- }
输出结果:
注意到结果没有输出“计算机网络”,那是因为wcstombs()不支持中文。
(2)方法二:使用WideCharToMultiByte();
- #include <iostream>
- using namespace std;
- #include <atlstr.h>
-
- int main()
- {
- CString str = L"liuxijiao计算机网络";
- int n = str.GetLength();
- int len = WideCharToMultiByte(CP_ACP, 0, str, n, NULL, 0, NULL, NULL);
- char *pChar = new char[len + 1];
- WideCharToMultiByte(CP_ACP, 0, str, n, pChar, len, NULL, NULL);
- pChar[len + 1] = '\0';
- cout<<pChar<<endl;
- delete[] pChar;
- return 0;
- }
输出结果:
二、char *转换为CString
(1)方法一:使用_T()宏
- CString str = _T("liuxijiao计算机网络");
(2)方法二:使用API的函数MultiByteToWideChar()
- #include <iostream>
- using namespace std;
- #include <atlstr.h>
- #include <stdio.h>
- #include <string.h>
-
- int main()
- {
-
- char *pChar = "liuxijiao计算机网络";
- int charLen = strlen(pChar);
- int len = MultiByteToWideChar(CP_ACP, 0, pChar, charLen, NULL, 0);
- wchar_t *pWChar = new wchar_t[len + 1];
- MultiByteToWideChar(CP_ACP, 0, pChar, charLen, pWChar, len);
- pWChar[len] = '\0';
-
-
- CString str;
- str.Append(pWChar);
-
- delete[] pChar;
- delete[] pWChar;
- return 0;
- }
在str.Append(pWChar);这条语句处设断点,调试运行,可查看到str的内容为"liuxijiao计算机网络"。
(三)方法三:使用A2T()、A2W()
- char *pChar = "liuxijiao计算机网络";
- USES_CONVERSION;
- CString str = A2T(pChar);
- char *pChar = "liuxijiao计算机网络";
- USES_CONVERSION;
- CString str = A2W(pChar);