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

c++server side programmingprogramming更新于 2025/4/26 23:22:17

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

示例

#include<iostream>
using namespace std;

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

输出

将给出输出 −

hello

要获取 char*,请使用 copy 函数。

示例

#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

相关文章