ในส่วนนี้ เราจะมาดูวิธีการแปลงสตริง C++ (std::string) เป็น const char* หรือ char* รูปแบบเหล่านี้เป็นสตริงสไตล์ C เรามีฟังก์ชันที่เรียกว่า c_str() นี้จะช่วยให้เราทำงาน ส่งคืนตัวชี้ไปยังอาร์เรย์ที่มีลำดับอักขระที่สิ้นสุดด้วยค่า null (เช่น สตริง C) ที่แสดงค่าปัจจุบันของวัตถุสตริง
ต่อไปนี้เป็นการประกาศสำหรับ std::string::c_str.
const char* c_str() const;
ฟังก์ชันนี้จะส่งกลับตัวชี้ไปยังอาร์เรย์ที่มีลำดับอักขระที่สิ้นสุดด้วยค่า null (เช่น สตริง C) ที่แสดงค่าปัจจุบันของวัตถุสตริง หากมีข้อยกเว้น สตริงจะไม่มีการเปลี่ยนแปลง
โค้ดตัวอย่าง
#include <iostream>
#include <cstring>
#include <string>
int main () {
std::string str ("Please divide this sentence into parts");
char * cstr = new char [str.length()+1];
std::strcpy (cstr, str.c_str());
char * p = std::strtok (cstr," ");
while (p!=0) {
std::cout << p << '\n';
p = std::strtok(NULL," ");
}
delete[] cstr;
return 0;
} ผลลัพธ์
Please divide this sentence into parts