CString 转换 String
时间: 2023-06-14 22:04:18 浏览: 79
在 MFC 中,可以使用 `CString` 类型的 `GetString()` 方法将其转换为 `const char*`,然后使用 `std::string` 的构造函数将其转换为 `std::string` 类型。
示例代码:
```cpp
CString cs = _T("Hello, World!");
const char* pszStr = cs.GetString();
std::string str(pszStr);
```
另外,也可以使用 ATL 中的 `CT2CA` 函数将 `CString` 转换为 `const char*`,然后再使用 `std::string` 的构造函数将其转换为 `std::string` 类型。
示例代码:
```cpp
#include <atlconv.h>
CString cs = _T("Hello, World!");
const char* pszStr = CT2CA(cs);
std::string str(pszStr);
```
相关问题
CString 转换成string
要将 CString 转换为 std::string,可以使用 CStringT 类模板的 GetString 方法。以下是一个示例代码:
```cpp
#include <iostream>
#include <atlstr.h> // 包含 CStringT 头文件
int main() {
CString str = "HelloWorld";
std::string convertedStr = CT2CA(str);
std::cout << "Converted string: " << convertedStr << std::endl;
return 0;
}
```
在上述示例代码中,我们使用了 ATL(Active Template Library)的 CStringT 类模板来进行字符串转换。`CT2CA` 是 CStringT 类模板的成员函数,用于将宽字符字符串(CString)转换为多字符字符串(std::string)。
在 `main` 函数中,我们创建了一个 CString 对象 "HelloWorld",然后使用 `CT2CA` 方法将其转换为 std::string 对象。
编译并运行上述代码,你将得到以下输出:
```
Converted string: HelloWorld
```
这样,你就可以将 CString 转换为 std::string。
cstring 转换 为 string
MFC CString 可以通过以下方式转换为 std::string:
1. 使用 CString 的 GetBuffer() 函数获取字符数组指针,然后通过 std::string 的构造函数进行转换。
例如:
```
CString cstr = "Hello, world!";
std::string str(cstr.GetBuffer());
```
2. 使用 CString 的 operator LPCSTR() 函数将 CString 转换为 LPCSTR 类型的指针,然后通过 std::string 的构造函数进行转换。
例如:
```
CString cstr = "Hello, world!";
std::string str(cstr.operator LPCSTR());
```
需要注意的是,CString 转换为 std::string 时需要考虑字符编码的问题,例如如果 CString 使用的是 Unicode 编码,则需要使用 std::wstring 进行转换。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)