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);

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