Converting String to Cstring in c++

吃可爱长大的小学妹 提交于 2019-12-03 19:05:24

问题


I am string to convert this string="apple", and want to put that into c-string of this style, char *c, that holds {a,p,p,l,e,'\0'}. Which Predefined method should I be using? Thank you ahead.


回答1:


.c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.




回答2:


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() works for immutable. The vector will manage the memory for you.




回答3:


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

I know this is not the predefined method but thought it may be useful to someone nevertheless.



来源:https://stackoverflow.com/questions/11821491/converting-string-to-cstring-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!