I have an error in my program: "could not convert from string to char*". How do I perform this conversion?
7 Answers
If you can settle for a const char*, you just need to call the c_str() method on it:
const char *mycharp = mystring.c_str(); If you really need a modifiable char*, you will need to make a copy of the string's buffer. A vector is an ideal way of handling this for you:
std::vector<char> v(mystring.length() + 1); std::strcpy(&v[0], mystring.c_str()); char* pc = &v[0]; Comments
Invoke str.c_str() to get a const char*:
const char *pch = str.c_str(); Note that the resulting const char* is only valid until str is changed or destroyed.
However, if you really need a non-const, you probably shouldn't use std::string, as it wasn't designed to allow changing its underlying data behind its back. That said, you can get a pointer to its data by invoking &str[0] or &*str.begin().
The ugliness of this should be considered a feature. In C++98, std::string isn't even required to store its data in a contiguous chunk of memory, so this might explode into your face. I think has changed, but I cannot even remember whether this was for C++03 or the upcoming next version of the standard, C++1x.
If you need to do this, consider using a std::vector<char> instead. You can access its data the same way: &v[0] or &*v.begin().
Comments
Since you wanted to go from a string to a char* (ie, not a const char*) you can do this BUT BEWARE: there be dragons here:
string foo = "foo"; char* foo_c = &foo[0]; If you try to modify the contents of the string, you're well and truly on your own.
2 Comments
If const char* is good for you then use this: myString.c_str()
If you really need char* and know for sure that char* WILL NOT CHANGE then you can use this: const_cast<char*>(myString.c_str())
If char* may change then you need to copy the string into something else and use that instead. That something else may be std::vector, or new char[], it depends on your needs.
Comments
std::string::c_str() returns a c-string with the same contents as the string object.
std::string str("Hello"); const char* cstr = str.c_str();