CString类型与string类型数据相互转换方法

1,CString类型 转化为 string类型

    string  = CString .getstring();

   注:CString .getstring() 转换为const char * 类型 系统在自动转换为 string类型;

2, string 类型 转化为 CString类型

    CString=  string.c_str();

转载于:https://www.cnblogs.com/chen-cqupt/p/4939702.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在C++中,可以使用一些方法将CString类型换为string类型,而不会丢失数据。下面介绍两种常用的转换方法: 1. CString换为string(MFC方式): - 首先,使用`CString`对象的`GetBuffer()`函数获取`const TCHAR*`指针。 - 然后,将获取到的指针传递给string类的构造函数,以创建一个新的string对象。 - 最后,使用`ReleaseBuffer()`函数释放CString对象的缓冲区。 ```cpp #include <iostream> #include <string> #include <afx.h> int main() { CString cstr = _T("Hello, CString!"); const TCHAR* buffer = cstr.GetBuffer(); std::string str(buffer); cstr.ReleaseBuffer(); std::cout << str << std::endl; return 0; } ``` 2. CString换为string(Unicode方式): - 首先,使用`WideCharToMultiByte`函数将Unicode字符串换为多字节字符串。 - 然后,使用换后的多字节字符串初始化string对象。 ```cpp #include <iostream> #include <string> #include <afx.h> int main() { CStringW cstr = L"Hello, CStringW!"; int length = WideCharToMultiByte(CP_UTF8, 0, cstr, -1, NULL, 0, NULL, NULL); char* buffer = new char[length]; WideCharToMultiByte(CP_UTF8, 0, cstr, -1, buffer, length, NULL, NULL); std::string str(buffer); delete[] buffer; std::cout << str << std::endl; return 0; } ``` 这两种方法可以将CString类型无损地换为string类型,并保留其中的数据。根据你的具体情况和使用的字符集,可以选择适合的方法进行换。 希望这些示例能够帮助你进行CStringstring换。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值