CString使用GetBuffer转换成std::string类型失败 原因

来源:互联网 发布:淘宝怎么养号快 编辑:程序博客网 时间:2024/06/05 02:34

cstr.GetBuffer(cstr.GetLength());

但是编译时会出现如下可能错误:
error C2440: “初始化”: 无法从“wchar_t *”转换为“std::basic_string<_Elem,_Traits,_Ax>”

或者

自己明明有#include <string>头文件,还是编译报错无法识别string类型

 

解决方法:

工程属性中的字符串模式 改为 ANSI 模式编译,如Use Multi-Byte Character Set。貌似新建应用程序默认用的是UNICODE编译。

#include  <string> 后,还得记得加上using namespace std;

 

MFC下的CString与wchar_t,还有它们与_T()或L等相关,网上搜索资料如下:
L表示UNICODE串,比如wchar_t* str = L"yangsongx"; 

_T在ANSI编译模式下表示ANSI串,在UNICODE下表示UNICODE串,

比如 
TCHAR* str = _T("yangsongx"); 
在ANSI下编译就是 char* str = "yangsongx"; 
在UNICODE下编译就是 wchar_t* str = L"yangsongx";

ANSI和UNICODE的区别

ANSI编码CString默认是窄字节的
UNICODE默认是宽字节的
std::string总是窄字节的

所以UNICODE下我们需要做宽窄字节转换
比如可以这样
USES_CONVERSION;
CString str;
std::string str1 = W2A(str.Getbuffer());
str.ReleaseBuffer();