user1112008
user1112008

Reputation: 442

C++ strings connecting with char arrays

Is this good way to do it?

char* array = "blah blah";
char* array2 = "bloh bloh";
string str = string() + array + array2;

Can't do direct string str = array + array2, can't add 2 pointers. Or should I do this

string str();
str += array;
str += array2;

Upvotes: 4

Views: 2545

Answers (2)

Luchian Grigore
Luchian Grigore

Reputation: 258568

There are lots of ways to do this:

string str(array);
str += array2;

or

string str = string(array) + array2;

or even

string str = array + string(array2);

or string streams:

stringstream ss;
ss << array << array2;

Upvotes: 3

NPE
NPE

Reputation: 500307

I would write:

string str = string(array) + array2;

Note that your second version is not valid code. You should remove the parentheses:

string str;
str += array;
str += array2;

Lastly, array and array2 should be of type constchar *.

Upvotes: 4

Related Questions