如何将 std::string 转换为 C++ 中的 const char* 或 char*?
您可以使用 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");
// Allocate memory
char* ccx = new char[s.length() + 1];
// Copy contents
std::copy(s.begin(), s.end(), ccx)
cout << ccx;
}输出
这将产生以下输出 -
hello
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP