我所使用的开发工具是Visual Studio 2013,在建立MFC应用程序时,工程默认字符集是使用Unicode字符集的,如下图:
而我们学习C/C++语言时常常使用的char类型字符串是基于ANSI,这在有些时候使我们在基于两种不同字符集的字符串之间进行转换有些不适应。例如CString和char之间的相互转换。
我们知道Unicode是使用两个字节来表示一个字符的,与ANSI用一个字节来存放一个字符相比,可以表示更多的字符,这就使Unicode表示各国语言成为可能,从而也就成为了一种通用的字符集了。
那么在这两种类型的字符串间的转换本质上都是存储空间分配的问题,也就是如何将两个字节表示的字符,用一个字节来表示。当然这种转换仅对英文有用,对于中文来说,如何硬要转换成ANSI,那就只能是乱码了。
下面是我参考网上资料,整理的个人认为最符合这个原理的转换方法,只需新建一个控制台工程,把下面的文件加入,运行,就可以自己测试一下我的想法是不是正确的:
#include
void main()
{
/***char -> CString***/
char szText[100] = "I am WangZhizhou.";
//Method 1
{
USES_CONVERSION;
CString strMethod1;
strMethod1 = A2T(szText);
MessageBox(NULL, strMethod1, L"char -> CString Method 1", 0);
}
//Method 2
CString strMethod2;
strMethod2 = szText;
MessageBox(NULL, strMethod2, L"char -> CString Method 2", 0);
//Method 3
CString strMethod3;
int nCharLen = strlen(szText);
int nStrLen = MultiByteToWideChar(CP_ACP, 0, szText, nCharLen, NULL, 0);
TCHAR* pStrTCHAR = new TCHAR[nStrLen + 1];
MultiByteToWideChar(CP_ACP, 0, szText, nCharLen, pStrTCHAR, nStrLen);
pStrTCHAR[nStrLen] = '\0';//Caution: the index is not the "nStrLen+1"
strMethod3.Append(pStrTCHAR);
MessageBox(NULL, strMethod3, L"char -> CString Method 3", 0);
delete[] pStrTCHAR;
/***CString -> char***/
CString strText = _T("I need a girl friend! ");
//Method 1
{
USES_CONVERSION;
char* pszMethod1 = T2A(strText);
MessageBoxA(NULL, pszMethod1, "CString -> char Method 1", 0);
}
//Method 2
int nLen=WideCharToMultiByte(CP_ACP, 0, strText, strText.GetLength(), NULL, 0,NULL,NULL);
char *pszMethod2 = new char[nLen + 1];
WideCharToMultiByte(CP_ACP, 0, strText, strText.GetLength(), pszMethod2, nLen,NULL,NULL);
pszMethod2[nLen] = '\0';//Caution: The subscript is not the "nLen+1"
MessageBoxA(NULL, pszMethod2, "CString -> char Method 2", 0);
delete[] pszMethod2;
}