std::string 如何转为const char *
时间: 2023-08-11 13:06:33 浏览: 56
可以使用std::string的c_str()成员函数将std::string转换为const char *类型。例如:
```c++
#include <iostream>
#include <string>
int main()
{
std::string s = "hello world";
const char *c_str = s.c_str(); // 将string类型转换为const char *类型
std::cout << c_str << std::endl;
return 0;
}
```
输出:
```
hello world
```
需要注意的是,c_str()函数返回的const char *指针指向的是std::string对象内部的字符数组,因此当std::string对象被销毁时,指针指向的字符数组也会被销毁。在使用c_str()函数返回的指针时,需要确保std::string对象的生命周期足够长,否则可能会出现未定义的行为。
相关问题
std::string 转 const char*
可以使用 std::string 的 c_str() 函数将其转换为 const char* 类型,例如:
```c++
std::string str = "hello world";
const char* cstr = str.c_str();
```
这样就可以将 std::string 类型的 str 转换为 const char* 类型的 cstr。需要注意的是,c_str() 函数返回的指针只在当前 std::string 对象存在期间有效,一旦 std::string 对象被销毁,c_str() 返回的指针也就失效了。
std::string to const char *
std::string 可以通过 c_str() 函数转换为 const char *,例如:
std::string str = "Hello, world!";
const char *cstr = str.c_str();
这样就可以将 std::string 对象 str 转换为 const char * 类型的指针 cstr,方便在 C 语言中使用。