开发者

C++ char * to string [duplicate]

开发者 https://www.devze.com 2023-01-09 22:51 出处:网络
This question already has answers here: Closed 12开发者_如何学Go years ago. Possible Duplicate: how to copy char * into a string and vice-versa
This question already has answers here: Closed 12开发者_如何学Go years ago.

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


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;


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消