Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string '+' : cannot add two pointers

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

like image 601
Andrey Zakcharenko Avatar asked Dec 19 '22 00:12

Andrey Zakcharenko


2 Answers

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.

like image 162
mastov Avatar answered Dec 30 '22 00:12

mastov


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";
like image 27
Baum mit Augen Avatar answered Dec 29 '22 22:12

Baum mit Augen