1. 程式人生 > >Unicode下的CString與char *轉換

Unicode下的CString與char *轉換

轉載:http://blog.sina.com.cn/s/blog_63106cd80100yq8n.html

在VS2005及以上的環境中,所見工程的預設字符集形式是Unicode,而VC6.0中,字符集形式為多位元組字符集(MBCS: Multi-Byte Character Set),這樣導致了許多字元轉換的方法在Unicode的環境中不允許使用,強制型別轉換的結果也會變得非常奇怪。

如LPCTSTR與Char *的轉換,在ANSI(VC6.0環境下預設編碼)下,LPCTSTR == const char*

但在Unicode下,LPCTSTR == const TCHAR*

 

如果覺得轉換麻煩的話,可以直接在新建工程時不選用Unicode Libraries,或者工程中修改 Project->Property->Configuration Properties->General->Project Defaults->Character Set,改為Use Multi-Byte Character Set。(此介面 alt+F7可以直接開啟)

 

問題就是,如果開發到一半,修改其中的預設編碼方式,程式會變得相當奇怪,而且,有很多字串常量需要去掉"_T()",所以,還是有必要記下Unicode中CString到Char *的轉換方法的。

 

方法1:使用API:WideCharToMultiByte進行轉換(使用過,有效)

CString str= CString("This is an example!");

int n = str.GetLength(); //按字元計算,str的長度

int len = WideCharToMultiByte(CP_ACP,0,str,n,NULL,0,NULL,NULL);//按Byte計算str長度

char *pChStr = new char[len+1];//按位元組為單位

WideCharToMultiByte(CP_ACP,0,str,n,pChStr,len,NULL,NULL);//寬位元組轉換為多位元組編碼

pChStr[len] = '\0';\\不要忽略末尾結束標誌

//用完了記得delete []pChStr,防止記憶體洩露

 

方法2:使用函式:T2A,W2A(未嘗試)

CString str= CString("This is an example!");

USES_CONVERSION//宣告標示符

//呼叫函式,T2A和W2A均支援ATL和MFC中字元轉換

char *pChStr = T2A(str);

//char *pChStr = W2A(str);//也可以實現轉換

 

注意:有時候需要包含標頭檔案 #include <afxpriv.h>

 

詳細的內容參考:http://wenku.baidu.com/view/cb061a1352d380eb62946d68.html

 

順便記一下各種型別轉為CString的方法:

CString str = CString("This is an example!");

CString str = _T("This is an ")+"an example";

int x = 9;CString str; str.Format(_T("%d"), x);

double x=9.7, CString str; str.Format(_T("%.3f"),x);