C++中将字符串转换为Cstring

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11821491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:35:31  来源:igfitidea点击:

Converting String to Cstring in C++

c++stringc-strings

提问by teamaster

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

我有一个要转换的字符串,string = "apple"并想将其放入这种样式的 C 字符串中char *c, , 包含{a, p, p, l, e, '\0'}. 我应该使用哪种预定义方法?

回答by Yann Ramin

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

.c_str()返回一个const char*. 如果你需要一个可变版本,你需要自己制作一个副本。

回答by bytemaster

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.

.c_str() 适用于不可变。该向量将为您管理内存。

回答by Ritchie Shatter

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()] = '##代码##';//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.

我知道这不是预定义的方法,但认为它可能对某人有用。