现在的位置: 首页 > 综合 > 正文

MFC:UNICODE下CString与char* ,string类型

2018年11月01日 ⁄ 综合 ⁄ 共 875字 ⁄ 字号 评论关闭

小菜初用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;

Unicode下 string 转换为 CString 类型:

string s1="hello";
CString s2=CString(s1.c_str());

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>

相应的,Unicode下 char* 转换为 CString 需用函数A2T、W2T:

char *c="hello";
USES_CONVERSION;
CString s=A2T(c);
//CString s=A2W(c);

抱歉!评论已关闭.