Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

    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?

like image 949
Aquarius_Girl Avatar asked Jun 02 '11 11:06

Aquarius_Girl


3 Answers

You can just re-assign:

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

std::string str(buf1);

str = buf2; // Calls str.operator=(const char *)
like image 171
Oliver Charlesworth Avatar answered Sep 20 '22 21:09

Oliver Charlesworth


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

like image 37
Aquarius_Girl Avatar answered Sep 21 '22 21:09

Aquarius_Girl


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";
like image 36
Bo Persson Avatar answered Sep 20 '22 21:09

Bo Persson