string s;
s += "#" + ','; //give error
s += "#" + ","; //give error
s += to_string(23) + ','; //no error
What is the proper way to concatenate new characters and strings to an existing string using + operator and when will it throw error? Can someone also shed light how append() and push_back() are different from "+" and which is the most optimal way?
Case 1
Here we consider the statement
s += "#" + ',';.The problem is that
operator+has higher precedence thanoperator+=. This means thats += "#" + ','is equivalent to writingNow,
"#"is a string literal of typeconst char [2]while','is a character literal of typechar. So basically, in this case you're trying to add a string literal to a char. Now, when you do this, string literal decays to aconst char*and the character literal is promoted toint.Essentially, this adds a
const char*to anint. The result of this is used as an operand of+=.More about this can be read at C++ Adding String Literal to Char Literal
Case 2
Here we consider the statement
s += "#" + ",";.In this case also the statement
s += "#" + ",";is equivalent to writing:due to operator precedence.
But in this case both the operand to
operator+are of typeconst char [2].So essentially, you're trying to add two string literals here. But there is no overloaded
operator+that takes two string literals orconst char*so this gives the mentioned error:Solution
There are several ways to solve this one of which include to add suffix
safter the string literal as shown below:Another way is to explicitly write
std::string("#").