如何在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP