如何在 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*,请使用 copy 函数。
示例
#include<iostream>
using namespace std;
int main() {
string x("hello");
// Allocate memory
char* ccx = new char[s.length() + 1];
// Copy contents
std::copy(s.begin(), s.end(), ccx)
cout << ccx;
}输出
这将生成以下输出 -
hello
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP