-1
const char * tag1[]={"abc","xyz"};

how to convert tag1 in std::string?

std::string tag2(tag1)

it simply copies tag1[0] to tag2. what i want is to convert the whole tag1 array into string.

Any ideas or workaround?

cpplearner
  • 11,873
  • 2
  • 42
  • 63
secretgenes
  • 1,191
  • 1
  • 17
  • 35

1 Answers1

4

Since you want to merge array of C-strings into one std::string, you can do this:

std::string tag2;   
for (auto ptr : tag1) {
    tag2.append(ptr);   
}

Iterate over C-strings array and append them to destination std::string.

Direct copy of tag1 array to pre-allocated std::string won't work because of null-terminators at end of each C-string in tag1. You will get abc\0xyz, instead of abcxyz

Starl1ght
  • 4,312
  • 1
  • 17
  • 48
  • 1
    probably calculating the total size and reserving is a bit more efficient without carpifying the code much – David Haim Nov 29 '16 at 09:58