Dùng phương thức c_str() của lớp string để lấy const char* chứa nội dung chuỗi.
Ví dụ: const char*
#include <iostream>
using namespace std;
int main() {
string x("hello");
const char* ccx = x.c_str();
cout << ccx;
}Đầu ra
hello
Để lấy char*, dùng hàm copy.
Ví dụ: char*
#include <iostream>
#include <algorithm> // for std::copy
using namespace std;
int main() {
string x("hello");
// Cấp phát bộ nhớ
char* ccx = new char[x.length() + 1];
// Sao chép nội dung
std::copy(x.begin(), x.end(), ccx);
ccx[x.length()] = '\0'; // kết thúc chuỗi
cout << ccx;
delete[] ccx; // giải phóng
}Đầu ra
hello