How do I convert a string to a char* in c++?

I have an error in my program: "could not convert from string to char*". How do I perform this conversion?

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

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().


//assume you have an std::string, str. 
char* cstr = new char[str.length() +1]; 
strcpy(cstr, str.c_str()); 

//eventually, remember to delete cstr
delete[] cstr; 

Use the c_str() method on a string object to get a const char* pointer. Warning: The returned pointer is no longer valid if the string object is modified or destroyed.


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.


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.


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

Need Your Help

Portability of Native C++ properties

c++ visual-c++ gcc properties c++11

In Visual Studio, there is __declspec(property) which creates properties similar to C#. Borland C++ offers the __property keyword with the exact same functionality. In the C++0x, there is mention...