Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write C++ string into char* [duplicate]

Tags:

c++

string

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?

like image 985
Terry Li Avatar asked Dec 09 '11 16:12

Terry Li


2 Answers

Assuming buf is at least version.length() + 1 bytes in size:

strcpy(buf, version.c_str());
like image 156
hmjd Avatar answered Nov 15 '22 04:11

hmjd


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

like image 34
James Kanze Avatar answered Nov 15 '22 04:11

James Kanze