How to store a const char* in std :: string?

17,627

Solution 1

You can just re-assign:

const char *buf1 = "abc";
const char *buf2 = "def";

std::string str(buf1);

str = buf2; // Calls str.operator=(const char *)

Solution 2

Ah well, as I commented above, found the answer soon after posting the question :doh:

    const char* g;
    g = (const char*)buffer;

    std :: string str;
    str.append (g);

So, I can call append() function as many times (after using the clear()) as I want on the same object with "const char *".

Though the "push_back" function won't work in place of "append".

Solution 3

str is actually copying the characters from buffer2, so it is not connected in any way.

If you want it to have another value, you just assign a new one

str = "Hello";
Share:
17,627
Aquarius_Girl
Author by

Aquarius_Girl

Arts and Crafts.stackexchange.com is in public beta now. Join us!

Updated on July 31, 2022

Comments

  • Aquarius_Girl
    Aquarius_Girl almost 2 years
        char       *buffer1 = "abc";
    
        const char *buffer2 = (const char*) buffer;
    
        std :: string str (buffer2);
    

    This works, but I want to declare the std::string object i.e. str, once and use it many times to store different const char*.

    What's the way out?

  • CB Bailey
    CB Bailey almost 13 years
    assign would be more expressive (and shorter and clearer) then clear followed by append, but a simple assignment using = will work just as well.