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
245 views
in Technique[技术] by (71.8m points)

c++ - how to copy char * into a string and vice-versa

If i pass a char * into a function. I want to then take that char * convert it to a std::string and once I get my result convert it back to char * from a std::string to show the result.

  1. I don't know how to do this for conversion ( I am not talking const char * but just char *)
  2. I am not sure how to manipulate the value of the pointer I send in.

so steps i need to do

  1. take in a char *
  2. convert it into a string.
  3. take the result of that string and put it back in the form of a char *
  4. return the result such that the value should be available outside the function and not get destroyed.

If possible can i see how it could be done via reference vs a pointer (whose address I pass in by value however I can still modify the value that pointer is pointing to. so even though the copy of the pointer address in the function gets destroyed i still see the changed value outside.

thanks!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Converting a char* to a std::string:

char* c = "Hello, world";
std::string s(c);

Converting a std::string to a char*:

std::string s = "Hello, world";
char* c = new char[s.length() + 1];
strcpy(c, s.c_str());

// and then later on, when you are done with the `char*`:
delete[] c;

I prefer to use a std::vector<char> instead of an actual char*; then you don't have to manage your own memory:

std::string s = "Hello, world";
std::vector<char> v(s.begin(), s.end());
v.push_back(''); // Make sure we are null-terminated
char* c = &v[0];

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

...