如何在C ++中将std :: string转换为const char *或char *?

您可以使用字符串类的c_str()方法获取带有字符串内容的const char *。 

示例

#include<iostream>
using namespace std;

int main() {
   string x("hello");
   const char* ccx = x.c_str();
   cout << ccx;
}

输出结果

这将给出输出-

hello

要获取char *,请使用复制功能。

示例

#include<iostream>
using namespace std;

int main() {
   string x("hello");

   //分配内存
   char* ccx = new char[s.length() + 1];

   //复制内容
   std::copy(s.begin(), s.end(), ccx)
   cout << ccx;
}

输出结果

这将给出输出-

hello