I have this code behaving weirdly:
int main() {
string a = "TRY";
string b = "THIS";
a += b[0] + '!'; //This outputs "TRYu"?
//a = a + b[0] + '!'; //This outputs "TRYT!" as expected.
cout << a;
}
Shouldn’t the above two statements be the same?
No. Your first example is not equal to
But rather to
You know that a char is a numeric value. Since both
b[0]and'!'are chars,b[0] + '!'will NOT give you a concatenation but an addition (b[0] + 33, basically). Then you will try to append the ASCII character of codeb[0] + 33into your string. Sinceb[0]is'T'(ASCII 84), you end up with the character of ASCII code 117 :'u'.You will have to replace
'!'bystd::string("!")to fix the code and make a concatenation.