Hi all
how to covert 'std::string' to 'char * in c++
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.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
i want it to be modifiable, can you help?
Yes, but why not just use std::string?i want it to be modifiable, can you help?
As I said, you just need to copy over the characters.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
&buff[0] could be used as modifiable char arrayCode:std::string contents("something"); std::vector<char> buff(contents.begin(), contents.end());
All problems in computer science can be solved by another level of indirection,
except for the problem of too many layers of indirection.
– David J. Wheeler
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.DOes it mean i need to use "strcpy" function?
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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.
It is too clear and so it is hard to see.
A dunce once searched for fire with a lighted lantern.
Had he known what fire was,
He could have cooked his rice much sooner.
Good point. In fact, it will not be null terminated since vart's example copied the actual string elements based on an iterator pair.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: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);
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)