How to save 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 an object std :: string ie str, once and use it many times to store various char * constants.

Which exit?

+5
source share
4 answers

You can simply rewrite:

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

std::string str(buf1);

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

stractually copies characters from buffer2, so it is in no way related.

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

str = "Hello";
+1
source

, , : doh:

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

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

, append() ( clear()), , "const char *".

"push_back" "append".

+1

Make a class "MyString" that forms the String buffer. Have a constant of this class. and then u can reassign the value of the configured string buffer using the same constant.

0
source

All Articles