如何在 C++ 中將 std::string 轉換為 const char* 或 char*?
可以使用字串類的 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
廣告