我想将std::string转换为char*或char[]数据类型。

std::string str = "string";
char* chr = str;

结果:"错误:不能转换' std::string '到' char '…"

有什么方法可以做到这一点?


当前回答

严格说来,您不能“将std::string转换为char*或char[]数据类型”。

正如其他答案所示,你可以将std::string的内容复制到一个char数组中,或者对std::string的内容创建一个const char*,这样你就可以以“C风格”访问它。

如果你试图改变std::string的内容,std::string类型有所有的方法来做任何你可能需要做的事情。

如果你试图将它传递给某个接受char*的函数,则有std::string::c_str()。

其他回答

或者,你可以使用向量来获得一个可写的char*,如下所示;

//this handles memory manipulations and is more convenient
string str;
vector <char> writable (str.begin (), str.end) ;
writable .push_back ('\0'); 
char* cstring = &writable[0] //or &*writable.begin () 

//Goodluck  

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

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

它不会自动转换(感谢上帝)。您必须使用c_str()方法来获取C字符串版本。

std::string str = "string";
const char *cstr = str.c_str();

注意,它返回一个const char *;你不允许改变c_str()返回的c风格字符串。如果你想处理它,你必须先复制它:

std::string str = "string";
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());
// do stuff
delete [] cstr;

或者在现代c++中:

std::vector<char> cstr(str.c_str(), str.c_str() + str.size() + 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[]!

下面是Protocol Buffer的一个更健壮的版本

char* string_as_array(string* str)
{
    return str->empty() ? NULL : &*str->begin();
}

// test codes
std::string mystr("you are here");
char* pstr = string_as_array(&mystr);
cout << pstr << endl; // you are here