Possible Duplicate:
Convert std::string to const char* or char*
void setVersion(char* buf, std::string version) {
buf = version;
}
I'm trying to write the version string into the buf, but the code above gave me this error "cannot convert ‘std::string {aka std::basic_string}’ to ‘char*’ in assignment".
What is the simplest way to fix it?
Assuming buf
is at least version.length() + 1
bytes in size:
strcpy(buf, version.c_str());
First, there's a serious problem with the interface, since you don't
know how large buf
is. Without knowing this, there is no way you can
correctly write anything to it. If you're passed the length, you can do
something like:
void
setVersion( char* buffer, size_t size, std::string const& version )
{
size_t n = version.copy( buffer, size - 1 ); // leave room for final '\0'
buffer[ n ] = '\0';
}
Another possibility is that the intent is for you to set some global pointer; the given interface can't do this, since you have a copy of the pointer, but if you were given a reference to it, you might do:
void
setVersion( char*& buffer, std::string const& version )
{
if ( buffer != NULL ) {
delete [] buffer;
}
buffer = new char[ version.size() + 1 ];
size_t n = version.copy( buffer, std::string::npos );
buffer[ n ] = '\0';
}
(Other versions are possible, but you have to copy the string, to avoid lifetime issues.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With