小菜初用MFC,就被MFC中各种类型相互转换给难住了,查了网上的一些资料,现总结如下:
Unicode下 CString 转换为 string 类型:
CString s1=L"hello";
string s2=CT2A(s1.GetBuffer());//方法一
string s2( CW2A( s1.GetString() ) ); //方法二
CT2CA pszName(s1); string s2(pszName);//方法三
wstring ws(s1); string s2; s2.assign(ws.begin(), ws.end());//方法四
//需要声明命名空间:using namespace std;
- 1
- 2
- 3
- 4
- 5
- 6
Unicode下 string 转换为 CString 类型:
string s1="hello";
CString s2=CString(s1.c_str());
- 1
- 2
Unicode下 CString 转换为 char* 类型:
//使用函数:T2A、W2A
CString s = _T("hello");
//声明标识符
USES_CONVERSION;//必须要有
//调用函数,T2A和W2A均支持ATL和MFC中的字符转换
char * c = T2A(s);
//char * c = W2A(s); //也可实现转换
//注意:需要添加引用#include <atlconv.h>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
相应的,Unicode下 char* 转换为 CString 需用函数A2T、W2T:
char *c="hello";
USES_CONVERSION;
CString s=A2T(c);
//CString s=A2W(c);