在C++中將string轉(zhuǎn)換為char數(shù)組可以使用以下方法:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
const char *cstr = str.c_str();
char charArray[str.length()+1];
strcpy(charArray, cstr);
std::cout << "String: " << str << std::endl;
std::cout << "Char Array: " << charArray << std::endl;
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
char charArray[str.length()+1];
str.copy(charArray, str.length());
charArray[str.length()] = '\0'; // 添加字符串結(jié)束符
std::cout << "String: " << str << std::endl;
std::cout << "Char Array: " << charArray << std::endl;
return 0;
}
這兩種方法都可以將string對(duì)象轉(zhuǎn)換為char數(shù)組,可以根據(jù)具體的需求選擇合適的方法。