MFC中CString與Char類型字符串的相互轉換

    我所使用的開發工具是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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章