原文地址:http://fengqing888.blog.163.com/blog/static/330114162012016103558408/
你在vs2010中默認字符集是UNICODE字符集,CString中字符以wchar_t的形式來存儲的,而不是char。你在項目-》屬性-》配置屬性 有一個字符集,可以改字符集,改成多字節字符集就行了。
我在VC的unicode項目中使用如下代碼時,提示錯誤“error C2664: "gethostbyname": 不能將參數 1 從"CString"轉換為"const char *"”。
CString host; lpHost = gethostbyname(host);
最快的解決辦法:
Since this function requires Ansi string, I think you have to convert your Unicode one. There are different approaches. I would suggest trying this simple MFC-based method:
CString yourString = . . .; CStringA ansiString = yourString; gethostbyname(ansiString);
I hope it works.
See also: CT2A macro, WideCharToMultiByte function.
其他方法:
CString,char*,const char *,LPCTSTR 的轉換
如何將CString類型的變量賦給char*類型的變量
1、GetBuffer函數:
使用CString::GetBuffer函數。
char *p; CString str="hello"; p=str.GetBuffer(str.GetLength()); str.ReleaseBuffer();
將CString轉換成char * 時
CString str("aaaaaaa"); strcpy(str.GetBuffer(10),"aa"); str.ReleaseBuffer();
當我們需要字符數組時調用GetBuffer(int n),其中n為我們需要的字符數組的長度.使用完成后一定要馬上調用ReleaseBuffer();
還有很重要的一點就是,在能使用const char *的地方,就不要使用char *
2、memcpy:
CString mCS=_T("cxl"); char mch[20]; memcpy(mch,mCS,20);
3、用LPCTSTR強制轉換: 盡量不使用
char *ch; CString str; ch=(LPSTR)(LPCTSTR)str; CString str = "good"; char *tmp; sprintf(tmp,"%s",(LPTSTR)(LPCTSTR)str);
4、
CString Msg; Msg=Msg+"abc"; LPTSTR lpsz; lpsz = new TCHAR[Msg.GetLength()+1]; _tcscpy(lpsz, Msg); char * psz; strcpy(psz,lpsz);
CString類向const char *轉換
char a[100]; CString str("aaaaaa"); strncpy(a,(LPCTSTR)str,sizeof(a));
或者如下:
strncpy(a,str,sizeof(a));
以上兩種用法都是正確地. 因為strncpy的第二個參數類型為const char *.所以編譯器會自動將CString類轉換成const char *.
CString轉LPCTSTR (const char *)
CString cStr; const char *lpctStr=(LPCTSTR)cStr;
LPCTSTR轉CString
LPCTSTR lpctStr; CString cStr=lpctStr;
將char*類型的變量賦給CString型的變量
可以直接賦值,如:
CString myString = "This is a test";
也可以利用構造函數,如:
CString s1("Tom");
將CString類型的變量賦給char []類型(字符串)的變量
1、sprintf()函數
CString str = "good"; char tmp[200] ; sprintf(tmp, "%s",(LPCSTR)str);
(LPCSTR)str這種強制轉換相當於(LPTSTR)(LPCTSTR)str
CString類的變量需要轉換為(char*)的時,使用(LPTSTR)(LPCTSTR)str
然而,LPCTSTR是const char *,也就是說,得到的字符串是不可寫的!將其強制轉換成LPTSTR去掉const,是極為危險的!
一不留神就會完蛋!要得到char *,應該用GetBuffer()或GetBufferSetLength(),用完后再調用ReleaseBuffer()。
2、strcpy()函數
CString str; char c[256]; strcpy(c, str); char mychar[1024]; CString source="Hello"; strcpy((char*)&mychar,(LPCTSTR)source);