cstring转string
时间: 2023-10-03 22:05:56 浏览: 41
可以使用`std::string`的构造函数将`char*`或`const char*`类型的字符串转换为`std::string`类型。
例如:
```cpp
#include <cstring>
#include <string>
int main() {
const char* cstr = "Hello, world!";
std::string str(cstr);
return 0;
}
```
如果要将`CString`类型的字符串转换为`std::string`,可以先将其转换为`const char*`类型,然后再使用上述方法。
例如:
```cpp
#include <string>
#include <atlstr.h>
int main() {
CString cstr = _T("Hello, world!");
std::string str(CT2A(cstr));
return 0;
}
```
其中,`CT2A`是`ATL`库中的一个函数,用于将`CString`类型的字符串转换为`const char*`类型的字符串。
相关问题
CString 转string
CString 转 string 可以通过以下几种方法实现:
1. 使用 CString 的 GetBuffer() 和 ReleaseBuffer() 函数:
CString cs = _T("abcde");
std::string str(cs.GetBuffer(cs.GetLength()));
cs.ReleaseBuffer();
\[1\]
2. 使用 CString 的 Format() 函数:
CString cs = _T("abcde");
std::string str;
str.Format("%s", cs);
\[3\]
3. 使用 CString 的 CStringA 类型:
CString cs = _T("abcde");
std::string str(CT2A(cs));
\[2\]
请注意,在使用 GetBuffer() 函数时,需要在使用完毕后调用 ReleaseBuffer() 函数来释放缓冲区所占的空间。另外,使用 CStringA 类型可以直接将 CString 转换为 std::string 类型。
#### 引用[.reference_title]
- *1* *2* *3* [string 与 CString 转化](https://blog.csdn.net/red10057/article/details/6401420)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
Cstring转string
Cstring转string的方法有多种,以下是其中两种常用的转换方式:
1. 使用CString的GetString()方法获取LPCTSTR类型的指针,然后将其传递给string的构造函数进行转换:
```
CString cstr;
string str(cstr.GetString());
```
2. 使用CStringA的GetString()方法获取LPCSTR类型的指针,然后将其传递给string的构造函数进行转换:
```
CStringA cstrA(cstr);
string str(cstrA.GetString());
```
相关推荐
![cs](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)