4

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;
user1112008
  • 432
  • 10
  • 27
  • no, mixing low-level and high level types is not good. – usoban May 09 '12 at 16:48
  • By the way, this code isn’t valid C++ any more (with C++11), and should generate warnings even when using older C++ for the use of deprecated non-const `char*` literals. Furthermore, the second code doesn’t compile anyway due to the [most vexing parse](http://stackoverflow.com/q/1424510/1968). – Konrad Rudolph May 09 '12 at 16:50
  • 1
    @usoban: There is a reason that `std::string` defines a conversion from `char*` to `std::string`. Sometimes you have a `char*` to deal with and there's no way around it. – Ed S. May 09 '12 at 16:50

2 Answers2

4

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

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

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;
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625