我有一个字符串要转换,string = "apple",我想把它放到一个包含{a, p, p, l, e, '\0'}的,这种风格的C字符串,char *c中。我应该使用哪种预定义的方法?
发布于 2012-08-06 09:10:21
.c_str()返回一个const char*。如果你需要一个可变的版本,你需要自己制作一个副本。
发布于 2012-08-06 09:54:46
vector<char> toVector( const std::string& s ) {
string s = "apple";
vector<char> v(s.size()+1);
memcpy( &v.front(), s.c_str(), s.size() + 1 );
return v;
}
vector<char> v = toVector(std::string("apple"));
// what you were looking for (mutable)
char* c = v.data();.c_str()适用于不可变的。向量将为您管理内存。
发布于 2015-05-15 21:18:33
string name;
char *c_string;
getline(cin, name);
c_string = new char[name.length()];
for (int index = 0; index < name.length(); index++){
c_string[index] = name[index];
}
c_string[name.length()] = '\0';//add the null terminator at the end of
// the char array我知道这不是预定义的方法,但我认为它可能对某些人有用。
https://stackoverflow.com/questions/11821491
复制相似问题