为什么能用LPCSTR强制类型转换CString到string,LPSTR却不行?
CString cStr = "hello world";
string sStr;sStr = LPCSTR(cStr);编译能通过。
把LPCSTR换成LPSTR编译错误,这是为什么呢?另:CString的成员函数GetBuffer的参数到底有什么作用?
MSDN上注释为:The minimum size of the character buffer in characters. This value does not include space for a null terminator.但我却不太理解,请高手举例说明?
CString cStr = "hello world";
string sStr;sStr = LPCSTR(cStr);编译能通过。
把LPCSTR换成LPSTR编译错误,这是为什么呢?另:CString的成员函数GetBuffer的参数到底有什么作用?
MSDN上注释为:The minimum size of the character buffer in characters. This value does not include space for a null terminator.但我却不太理解,请高手举例说明?
2.获取CString的数据成员地址,可以向里面写数据,用完后要调用ReleaseBuffer();
如:
CString str;
strcpy(str.GetBuffer(256), "test!");
str.ReleaseBuffer();
CString 是MFC的字符串,在vc6 时代,是ascii,对应的是char;在vc.net后,是unicode的了对应的是wchar。
string 应该是stl,是ascii的,对应的unicode字符串是wstring。我不知道楼主的做法结果是否正确了,原先的老方法都会采用api或者ole2a a2c(大些字母)这类宏来搞定
LPCSTR和LPSTR区别是前者是const,到tchar.h中看一下就明白了
第二:强制转换有安全隐患,不是优良的代码风格。CString类有Getbuffer和Getstring方法,string类有c_str方法,为什么很多人不用?
CString类本身的构造函数就能够转换UNICODE和ANSI,为什么许多人还在用强制转换得出错误结果?或者即使正确也是很麻烦的使用API?
不太理解……记住,Getbuffer和Getstring方法,还有c_str方法,都能够获得内置类型的字符指针char*或wchar_t*,只要走到内置类型这一步,一切不都迎刃而解了么?
CString to string:
CString str1;
ANSI的情况,即CString为CStringA
string str2(str1.GetString());或string str2=str1.GetString();
UNICODE情况,即CString为CStringW
CString str1;
CStringA str1A(str1);
string str2(str1A.GetString());或string str2=str1A.GetString();
GetBuffer也可以,不同的是GetString返回的是const值。
string to CString
string str1;
CString str2(str1.c_str());或者CString str2=str1.c_str();
无论是string还是wstring,上述语句都可以将内容读进CString
请注意LPCSTR 和LPSTR的区别,一个是const 类型,一个不是的,你用LPSTR 就是类型不一致了
VS2005里面的CString不同时支持宽字符串吗?