Why assignment
std::string s="aaa"+1
works fine while
std::string s="aaa"+1+"bbb"
gets error Error 14 error C2110: '+' : cannot add two pointers
There is no +
operator to concatenate C strings. C strings are just pointers (const char *
), so if you add a number to it, it will just increment that pointer. Afterwards you convert it to a C++ string:
std::string s = "aaa" + 1
|=======|
"aa"
const char *
|==============|
"aa"
std::string
Then in the second step it fails, when you try to concatenate the second string because while adding a constant to a pointer still made some sense (even though not in your case), there is no way you can make sense of adding two pointers.
"aaa" + 1 + "bbb"
|========|
"aa"
const char *
|===|
const char *
To make sure you actually concatenate and don't sum pointers, I'd suggest using a stringstream
. This also makes sure your constant number is converted properly to a string
.
std::stringstream ss;
ss << "aaa" << 1 << "bbb";
std::string s = ss.str();
This will work for every type that has the operator<<
overloaded.
std::string s="aaa"+1;
This just compiles, but most likely does not do what you want: It adds 1 to the const char*
the literal "aaa"
decays to and then constructs the std::string
from that pointer, resulting in s == "aa"
.
When using operator+
to concatenate strings, at least one of the operands must have type std::string
, the other one may be const char*
or something convertible to that. For example:
std::string s="aaa"+std::to_string(1);
or
std::string s="aaa"+std::to_string(1)+"bbb";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With