ใช้เมธอด c_str() ของคลาส string เพื่อได้ const char*
ตัวอย่าง: ได้ const char*
#include <iostream>
using namespace std;
int main() {
string x("hello");
const char* ccx = x.c_str();
cout << ccx;
}
ผลลัพธ์
hello
ตัวอย่าง: ได้ char* (ต้องจัดสรรหน่วยความจำเอง)
#include <iostream>
#include <algorithm> // สำหรับ copy
using namespace std;
int main() {
string x("hello");
// จัดสรรหน่วยความจำ +1 สำหรับ null terminator
char* ccx = new char[x.length() + 1];
// คัดลอกเนื้อหา
std::copy(x.begin(), x.end(), ccx);
ccx[x.length()] = '\0'; // ต้องเพิ่ม null terminator เอง
cout << ccx;
delete[] ccx; // อย่าลืมลบ!
}
ผลลัพธ์
hello
ข้อควรระวัง: c_str() คืน pointer ไปยัง internal buffer ของ string ห้าม modify และอาจ invalid เมื่อ string ถูกแก้ไขหรือทำลาย สำหรับ char* ต้องจัดการ memory เอง