我想将std::string转换为char*或char[]数据类型。
std::string str = "string";
char* chr = str;
结果:"错误:不能转换' std::string '到' char '…"
有什么方法可以做到这一点?
我想将std::string转换为char*或char[]数据类型。
std::string str = "string";
char* chr = str;
结果:"错误:不能转换' std::string '到' char '…"
有什么方法可以做到这一点?
当前回答
If you just want a C-style string representing the same content: char const* ca = str.c_str(); If you want a C-style string with new contents, one way (given that you don't know the string size at compile-time) is dynamic allocation: char* ca = new char[str.size()+1]; std::copy(str.begin(), str.end(), ca); ca[str.size()] = '\0'; Don't forget to delete[] it later. If you want a statically-allocated, limited-length array instead: size_t const MAX = 80; // maximum number of chars char ca[MAX] = {}; std::copy(str.begin(), (str.size() >= MAX ? str.begin() + MAX : str.end()), ca);
string不会隐式转换为这些类型,原因很简单,需要这样做通常是一种设计风格。确保你真的需要它。
如果你确实需要一个char*,最好的方法可能是:
vector<char> v(str.begin(), str.end());
char* ca = &v[0]; // pointer to start of vector
其他回答
为了完整起见,不要忘记std::string::copy()。
std::string str = "string";
const size_t MAX = 80;
char chrs[MAX];
str.copy(chrs, MAX);
std::string::copy()不终止NUL。如果你需要确保在C字符串函数中使用NUL终止符:
std::string str = "string";
const size_t MAX = 80;
char chrs[MAX];
memset(chrs, '\0', MAX);
str.copy(chrs, MAX-1);
如果我需要c++字符串内容的可变原始副本,那么我会这样做:
std::string str = "string";
char* chr = strdup(str.c_str());
后来:
free(chr);
So why don't I fiddle with std::vector or new[] like anyone else? Because when I need a mutable C-style raw char* string, then because I want to call C code which changes the string and C code deallocates stuff with free() and allocates with malloc() (strdup uses malloc). So if I pass my raw string to some function X written in C it might have a constraint on it's argument that it has to allocated on the heap (for example if the function might want to call realloc on the parameter). But it is highly unlikely that it would expect an argument allocated with (some user-redefined) new[]!
orlp的char*答案的安全版本使用unique_ptr:
std::string str = "string";
auto cstr = std::make_unique<char[]>(str.length() + 1);
strcpy(cstr.get(), str.c_str());
(这个答案只适用于c++ 98。)
请不要使用原始的char*。
std::string str = "string";
std::vector<char> chars(str.c_str(), str.c_str() + str.size() + 1u);
// use &chars[0] as a char*
使用c_str()成员函数从std::string对象中获取const char *类型:
std::string str = "string";
const char* chr = str.c_str();
要从std::string中获得非const char *,可以使用data()成员函数,该函数从c++ 17开始返回一个非const指针:
std::string str = "string";
char* chr = str.data();
对于该语言的旧版本,您可以使用范围构造将字符串复制到一个vector中,从中可以获得非const指针:
std::string str = "string";
std::vector<char> str_copy(str.c_str(), str.c_str() + str.size() + 1);
char* chr = str_copy.data();
但要注意,这不会让你修改包含在str中的字符串,只有副本的数据可以这样改变。请注意,在旧版本的语言中使用c_str()是特别重要的,因为当时std::string在调用c_str()之前不能保证以null结尾。