Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to convert a std::string into a char* or char[] data type.

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

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

Results in: “error: cannot convert 'std::string' to 'char' ...” .

(结果: “错误:无法将'std :: string'转换为'char'...” 。)

What methods are there available to do this?

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

  ask by Mario translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
203 views
Welcome To Ask or Share your Answers For Others

1 Answer

It won't automatically convert (thank god).

(它不会自动转换(感谢上帝)。)

You'll have to use the method c_str() to get the C string version.

(您必须使用方法c_str()来获取C字符串版本。)

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

Note that it returns a const char * ;

(请注意,它返回一个const char * ;)

you aren't allowed to change the C-style string returned by c_str() .

(您不能更改c_str()返回的C样式字符串。)

If you want to process it you'll have to copy it first:

(如果你想处理它,你必须先复制它:)

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

Or in modern C++:

(或者在现代C ++中:)

std::vector<char> cstr(str.c_str(), str.c_str() + str.size() + 1);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...