Unicode下CString和char *之间的互相转换
1. 调用 WideCharToMultiByte() API











CString str = _T("D://校内项目//QQ.bmp");
//注意:以下n和len的值大小不同,n是按字符计算的,len是按字节计算的
int n = str.GetLength(); // n = 14, len = 18
//获取宽字节字符的大小,大小是按字节计算的
int len = WideCharToMultiByte(CP_ACP,0,str,str.GetLength(),NULL,0,NULL,NULL);
//为多字节字符数组申请空间,数组大小为按字节计算的宽字节字节大小
char * pFileName = new char[len+1]; //以字节为单位
//宽字节编码转换成多字节编码
WideCharToMultiByte(CP_ACP,0,str,str.GetLength(),pFileName,len,NULL,NULL);
pFileName[len+1] = '/0'; //多字节字符以'/0'结束
eg.2
- #include <iostream>
- using namespace std;
- #include <atlstr.h>
- int main()
- {
- CString str = L"liuxijiao计算机网络";
- int n = str.GetLength(); //获取str的字符数
- 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'; //多字节字符以'\0'结束
- cout<<pChar<<endl;
- delete[] pChar;
- return 0;
- }
2. 调用CRT函数wcstombs()





- #include <iostream>
- using namespace std;
- #include <atlstr.h>
- int main()
- {
- CString str = L"liuxijiao计算机网络";
- wchar_t *pWChar = str.GetBuffer(); //获取str的宽字符用数组保存
- str.ReleaseBuffer();
- int nLen = str.GetLength(); //获取str的字符数
- 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()不支持中文。
3. 使用CString构造器或赋值操作








4. 使用ATL串转换宏














二、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数组转换为wchar_t数组
- char *pChar = "liuxijiao计算机网络";
- int charLen = strlen(pChar); //计算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';
- //将wchar_t数组转换为CString
- CString str;
- str.Append(pWChar);
- delete[] pChar;
- delete[] pWChar;
- return 0;
- }