Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

How to convert a std::string to const char* or char* in C++?


ในส่วนนี้ เราจะดูวิธีแปลง C++ string (std::string) เป็น const char* หรือ char* รูปแบบเหล่านี้เป็น C-style strings เรามีฟังก์ชันชื่อ c_str() ฟังก์ชันนี้จะช่วยทำภารกิจนี้ มันคืนค่า pointer ไปยัง array ที่มี null-terminated sequence of characters (เช่น C-string) ที่แสดงค่าปัจจุบันของ string object

การประกาศสำหรับ std::string::c_str คือ

const char* c_str() const;

ฟังก์ชันนี้คืนค่า pointer ไปยัง array ที่มี null-terminated sequence of characters (เช่น C-string) ที่แสดงค่าปัจจุบันของ string object หากมี exception ถูก throw ไม่มีการเปลี่ยนแปลงใน string

ตัวอย่างโค้ด

#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