Writing C ++ string to char *

Possible duplicate:
Convert std :: string to const char * or char *

void setVersion(char* buf, std::string version) {
  buf = version;
}

I am trying to write a version string in buf, but the code above gave me this error "cannot convert" std :: string {aka std :: basic_string} to 'char * in assignment ".

What is the easiest way to fix it?

+4
source share
5 answers

Assuming it bufhas a size of at least version.length() + 1bytes:

strcpy(buf, version.c_str());
+13
source

-, , , buf. , - . , - :

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';
}

, ; , , , :

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';
}

( , , .)

+5

, buf

strcpy(buf,version.c_str())
+3

c_str() :

void setVersion(char* buf, std::string version) 
{
  buf = version.c_str();
}
+2

, , char * std::string - , vesrion.c_str().

If you want to copy it to a separate buffer — for the function signature used — the buffer must be allocated before the function is called and must have the same size as version.size () + 1.

Otherwise, you can do the following:

void setVersion ( char** out, std::string in ) {
    *out = new char[in.size() + 1];
    strcpy ( out, in.c_str() );
}

NTN

+1
source

All Articles