我想将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

其他回答

orlp的char*答案的安全版本使用unique_ptr:

std::string str = "string";
auto cstr = std::make_unique<char[]>(str.length() + 1);
strcpy(cstr.get(), str.c_str());

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

OOP风格的转换

converter.hpp

class StringConverter {
    public: static char * strToChar(std::string str);
};

converter.cpp

char * StringConverter::strToChar(std::string str)
{
    return (char*)str.c_str();
}

使用

StringConverter::strToChar("converted string")

更多细节在这里,还有这里,但你可以用

string str = "some string" ;
char *cstr = &str[0];

从c++ 11开始,还可以使用str.data()成员函数,该函数返回char *

string str = "some string" ;
char *cstr = str.data();

这可能是对bobobobo的回答的一个更好的评论,但我没有那个代表。它完成了同样的事情,但是使用了更好的实践。

虽然其他答案很有用,但如果你需要显式地将std::string转换为char*而不使用const, const_cast是你的朋友。

std::string str = "string";
char* chr = const_cast<char*>(str.c_str());

注意,这不会为您提供数据的副本;它会给你一个指向字符串的指针。因此,如果修改chr的一个元素,就会修改str。