1.CString转string
(1).使用函数T2A,W2A
CString cstrPath = L"D:\\Main\\Log\\Test.Log";
USES_CONVERSION;
std::string str(W2A(cstrPath));
(2).使用WideCharToMultiByte函数
CString cstrPath = L"D:\\Main\\Log\\Test.Log";
int n = cstrPath.GetLength(); //按字符计算,str的长度
int len = WideCharToMultiByte(CP_ACP,0,cstrPath,n,NULL,0,NULL,NULL);//按Byte计算str长度
char *pChStr = new char[len+1];//按字节为单位
WideCharToMultiByte(CP_ACP,0,cstrPath,n,pChStr,len,NULL,NULL);//宽字节转换为多字节编码
pChStr[len] = '\0';//不要忽略末尾结束标志
std::string str = pChStr;
delete []pChStr;
2.string转CString
CString cstrTemp;
string str = "D:\\Main\\Log\\Test.Log";
cstrTemp = const_cast<char*>(str.c_str());
cstrTemp = str.data();
3.CString转char*
由于CString属于WCHAR类型,即宽字符(16/32位),而char类型一般为8位,所以需要进行转换操作,方法有如下:
(1).利用WideCharToMultiByte函数进行转换
CString cstrPath = L"D:\\Main\\Log\\Test.Log";
int len = WideCharToMultiByte(CP_ACP,0,cstrPath,cstrPath.GetLength(),NULL,0,NULL,NULL);
char * pLogPath = new char[len+1]; //以字节为单位
WideCharToMultiByte(CP_ACP,0,cstrPath,cstrPath.GetLength(),pLogPath,len,NULL,NULL);
pLogPath[len] = '\0'; //多字节字符以'/0'结束
FILE *fp = fopen(pLogPath,"r");
(2).使用函数T2A,W2A,注意有时可能需要添加#include <afxpriv.h>
CString cstrPath = L"D:\\Main\\Log\\Test.Log";
USES_CONVERSION;
//调用函数,T2A和W2A均支持ATL和MFC中的字符转换
char * pLogPath = T2A(cstrPath);
FILE *fp = fopen(pLogPath,"r");
4.char*转CString
(1).利用MultiByteToWideChar函数
char* pLogPath = "D:\\Main\\Log\\Test.Log";
//计算char *数组大小,以字节为单位,一个汉字占两个字节
int charLen = strlen(pLogPath);
//计算多字节字符的大小,按字符计算。
int len = MultiByteToWideChar(CP_ACP,0,pLogPath,charLen,NULL,0);
//为宽字节字符数组申请空间,数组大小为按字节计算的多字节字符大小
TCHAR *buf = new TCHAR[len + 1];
//多字节编码转换成宽字节编码
MultiByteToWideChar(CP_ACP,0,pLogPath,charLen,buf,len);
buf[len] = '\0'; //添加字符串结尾,注意不是len+1
//将TCHAR数组转换为CString
CString str;
str.Append(buf);
//删除缓冲区
delete []buf;
MessageBox(str);
(2).使用函数:A2T,A2W
char* pLogPath = "D:\\Main\\Log\\Test.Log";
USES_CONVERSION;
CString str = A2T(pLogPath);
MessageBox(str);
5.string转char*
string str = "D:\\Main\\Log\\Test.Log";
char* pchTmp = (char*)str.data();
char* pchTmp1 = (char*)str.c_str();
6.char*转string,直接转换
char chTemp[MAX_PATH]="D:\\Main\\Log\\Test.Log";
string strTemp = chTemp;