MFC中CString 与 std::string 相互转化

-- URL https://www.cnblogs.com/whl2012/p/4811912.html

-- MFC中CString 与 std::string 相互转化
CString实际是CStringT, 也就是模板类,

在UNICODE环境下,实际是CStringW,

在多字符集环境下,实际是CStringA

std::string就是多字符集的.

UNICODE环境下
CStringW-->std::string
CString实际是CStringW,要转换成多字符集,需进行转码。使用WideCharToMultiByte 转换成多字符集,然后再构造std::string

std::string-->CStringW
因为CStringT模板类已经自动做了 char* 到 wchar_t* 的转码。

实例
复制代码
//使用Unicode 字符集
CString strCS("HelloWorld");
USES_CONVERSION;
std::string strS(W2A(strCS)); //CString-->std::string
CString strCStemp;
strCStemp = strS.c_str();//std::string-->CString
复制代码

注意:std::string-->CString时,不可以写在同一行:

CString strCStemp = strS.c_str();//ERROR
多字符集
CString 实际就是CStringA.

复制代码
//CStringA-->std::string
CString strCS("HelloWorld");
std::string strS;
strS = strCS.GetBuffer(0);

//std::string-->CStringA
CString strCStemp = strS.c_str();//注意,可写在同一行
复制代码

posted @   boyang987  阅读(422)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示