std::string to char*

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cstriker
    New Member
    • Mar 2008
    • 3

    std::string to char*

    Hi I am trying to convert a string to char* using casting.

    std::string str= "whatever";
    char* val = (char*) str.c_str();

    which compiles fine. But i end up with a const char despite casing it to a char*. I want to be able to append to this char array. Any ideas?

    Thank You
  • gpraghuram
    Recognized Expert Top Contributor
    • Mar 2007
    • 1275

    #2
    Originally posted by cstriker
    Hi I am trying to convert a string to char* using casting.

    std::string str= "whatever";
    char* val = (char*) str.c_str();

    which compiles fine. But i end up with a const char despite casing it to a char*. I want to be able to append to this char array. Any ideas?

    Thank You

    After getting thec_str() copy the value to a C string which has enough spaces to hold the same

    Raghuram

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      You do not use the c_str() method to get a char*. That method returns a const char*.

      Indead use the copy() method. That makes a copyu of the string object as a C-string. Be sure you have allocated enough memory first by calling the size() method. Add 1 to the size to allow for the null terminator and then allocate.

      Comment

      Working...