Hi all
how to covert 'std::string' to 'char * in c++
Printable View
Hi all
how to covert 'std::string' to 'char * in c++
You can "convert" a std::string to a const char* using the c_str() member function.
If you need a modifiable char* instead, then you have to copy over the characters.
i want it to be modifiable, can you help?
Yes, but why not just use std::string?Quote:
i want it to be modifiable, can you help?
As I said, you just need to copy over the characters.
&buff[0] could be used as modifiable char arrayCode:std::string contents("something");
std::vector<char> buff(contents.begin(), contents.end());
I have a standard function which nedds "char* " to be modifiable...
I didnt get what you mean by "copy over the characters."
DOes it mean i need to use "strcpy" function?
Yes, or you could use what vart suggested.Quote:
DOes it mean i need to use "strcpy" function?
ya i got it!!!!
Thanks alot ,laserlight & vast !!!!!
If the modified string will be larger than the original string and you're using a vector<char>, be sure to call vector's reserve() member function first to reserve enough space to store the new string...
>> I have a standard function which nedds "char* " to be modifiable
If it is a "standard" function, there's probably a better alternative that works on strings.
Not if you want to follow the standard. &buff[0] is a modifiable char array, but it is not guaranteed to be null terminated. On the other hand strcpy requires the string to be null terminated. So you should use &buff[0] if the string length is specified, and strcpy if the string must be null terminated.
Good point. In fact, it will not be null terminated since vart's example copied the actual string elements based on an iterator pair.Quote:
Not if you want to follow the standard. &buff[0] is a modifiable char array, but it is not guaranteed to be null terminated.
Or we could modify vart's example to:Quote:
On the other hand strcpy requires the string to be null terminated. So you should use &buff[0] if the string length is specified, and strcpy if the string must be null terminated.
Code:std::string contents("something");
std::vector<char> buff(contents.c_str(), contents.length() + 1);