Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

c++ - std :: string to char *(std::string to char*)

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

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

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...