字符类型之间的相互转化(1):
1.CString 转 CStringA
1) 使用UNICODE字符集编程时,可能需要使用到那些不支持UNICODE的库,此时就
需要将CString转成CStringA.
方法:
CString str1=_T("CSDN");;
CStringA str2;
str2=str1;
2)使用ANSI字符集编程时,CString 和 CStringA 类型相同
2.DWORD转CString(MFC IP控件)
方法:
DWORD m_lIpAddress;
CString strIpAddress;
strIpAddress.Format(_T("%d.%d.%d.%d"),((BYTE*) &m_lIpAddress)[3],((BYTE*)&m_lIpAddress)[2],((BYTE *)&m_lIpAddress)[1],((BYTE *)&m_lIpAddress)[0]);
3.CString转DWORD(MFC IP控件)
方法:先将CString转成CStringA,再转化成DWORD
CString m_strRemoteIpAddr;
CStringA Str2;
DWORD dwIP;
Str2 = m_strRemoteIpAddr;
dwIP = inet_addr(Str2.GetBuffer());
unsigned char*pIP = (unsigned char*)&dwIP;
m_strRemoteIP.SetAddress(*pIP, *(pIP + 1),*(pIP + 2),*(pIP + 3));
4.CString转CHAR
方法:
char* CStringToChar(CString strSrc)
{
#ifdef UNICODE
DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, strSrc.GetBuffer(0), -1, NULL, 0, NULL, FALSE);
strSrc.ReleaseBuffer();
char *psText;
psText = new char[dwNum];
if (!psText)
delete[]psText;
WideCharToMultiByte(CP_OEMCP, NULL, strSrc.GetBuffer(0), -1, psText, dwNum, NULL, FALSE);
strSrc.ReleaseBuffer();
return psText;
#else
LPCTSTR p = strSrc.GetBuffer(0);
strSrc.ReleaseBuffer();
char *psText;
psText = new char[strSrc.GetLength() + 1];
strcpy_s(psText, strSrc.GetLength() + 1, CT2CA(p));
if (!psText)
delete[]psText;
return psText;
#endif
}
5.string转CString
方法:
string strTest = "CSDN";
CString cstrTest;
cstrTest = CA2A(strTest.c_str());
6.CString转string
方法:
CString cstrTest = _T("CSDN");
string strTest;
strTest = CT2A(cstrTest.GetString());
7.const char*转CString
方法:
const char* cstrTest = "CSDN";
CString strTest(cstrTest);
8.CString转const char*
方法:
CString cstrTest = _T("CSDN");
USES_CONVERSION;
std::string str(W2A(cstrTest ));
const char* cstr = str.c_str();
9.string转const char*
方法:
string str = "CSDN";
const char* cstr = str.c_str();
10.const char*转string
方法:
const char* cstr = "CSDN";
string str(cstr);