MFC中怎样把CString类型转换成char*型

第一种

CString strTemp;char szTemp[128];

strTemp = _T("abckdkfei");

memset( szTemp, 0, sizeof(szTemp) );

strcpy( szTemp, strTemp.GetBuffer(strTemp.GetLength()) );

第二种:

char * pchar;CString str="hello";pchar=(LPSTR)(LPCSTR)str;

第三种:

char szTemp[500];

CString strTemp = "123456789";

memset(szTemp,0,sizeof(szTemp));

sprintf(szTemp,"%s",strTemp);

第四种:

如果是基于UNICODE的,那么直接强制转换是不行的,直接转换在基于MBCS的工程可以,而在基于UNICODE的工程是不行的,CString会以UNICODE的形式来保存数据,强制类型转换只会返回第一个字符。d

方法一:可以用API:WideCharToMultiByte进行转换

方法二:可以添加文件#include <afxpriv.h>然后这样:

CString strTest = _T("abcd");

USES_CONVERSION;

LPSTR lpszTest= T2A(strTest);

这样应该可以的



第六种

办法比较麻烦,可以试试WideCharToMultiByte,这种方法一般都有效。

CString str;

 DWORD dwNum = WideCharToMultiByte(CP_OEMCP,NULL,str,-1,NULL,NULL,0,NULL); 

char *c = new char[dwNum]; 

WideCharToMultiByte(CP_OEMCP,NULL,str,-1,c,dwNum,0,NULL








猜你喜欢

转载自blog.csdn.net/qq_35826851/article/details/80513035