views:

198

answers:

3

Possible Duplicate:
how to copy char * into a string and vice-versa

I have to pass a value into a method that required a char *

MyMethod(char * parameter)
{
    // code
}

However, the parameter I need to feed it is currently a std::string. How do I convert the std::string to a char *?

std::string myStringParameter = //whatever

char * myCharParameter = //Convert here somehow

MyMethod(myCharParameter);
+3  A: 

You are looking for the c_str() method:

char * myCharParameter = myStringParameter.c_str();

You might need to const_cast the return to get it into a char * instead of a const char *. Refrain from modifying the string though; it is the internal buffer of the std::string object. If you actually need to modify the string, you should use strncpy to copy it to another buffer:

char * myCharParameter = new char[myStringParameter.length() + 1];
strncpy(myCharParameter, myStringParameter.c_str(), myStringParameter.length() + 1);

// And later...
myStringParameter.assign(myCharParameter);
delete [] myCharParameter;
jdmichal
const char* to be precise.
seand
`c_str()` returns a `const char*`, not a `char *`.
James McNellis
@James McNellis Already addressed that in the question.
jdmichal
@jdmichal: If a function has a parameter of type `char*`, it may modify the object pointed to; using `const_cast` to cast away constness is very dangerous and is A Bad Idea.
James McNellis
Okay so a char is the same thing as a cstring? I thought cstring was a different type of object? I'm new to C++ so I'm still learning these things.
Jakobud
`char *` is sometimes called a "cstring". This is because all strings in C are stored that way.
jdmichal
@jdmichal + @Jakobud: There is also the `CString` class, which is shipped as part of MFC.
Billy ONeal
If MyMethod() takes a non-const string for a good reason, you probably want to persist whatever changes it made to `myCharParameter` back to `myStringParameter.`
JohnMcG
+1  A: 

It depends on whether MyMethod actually changes the string that's passed in.

If the only thing you know about it is the signature, then you have to assume it could change the string, and copy it into a temporary buffer per @jdmichal's answer.

It's also possible that the developer of this API didn't know or care about const correctness. So the function takes in a non-const buffer even though it doesn't change it.

If that's the case you can get by with:

MyMethod(const_cast<char*>(myStringParameter.c_str());

In my career I have come across more than a few API's taking in non-const strings that should have been const.

JohnMcG
A: 

If the function is actually going to modify the string, you'd better create a separate copy:

std::string str = // ...
char* cstr = strdup(str.c_str());
MyMethod(cstr);
// If you want to preserve the changes made:
// str = cstr;
free(cstr);
Michael Aaron Safyan