0

I was recently playing with strings, and I have come across a strange issue. During Operator overloading with + for String concatenation. I have tried to overload with two chars to a string. It returns me a peculiar behaviour.

string a = 'den';
a+='e'+'r';

I expect the result to be dener. But,it returns den╫. I like to know, what went wrong my approach. It works when, I tried it separate line, like below.

string a = 'den';
a+='e';
a+='r';

I got answer from a different question. But, I am repeating here, for anywork around to solve my problem.

Aswin
  • 137
  • 2
  • 9

2 Answers2

2
a+='e'+'r';

There are two operators involved. By their association rules, they work in the following order:

  1. 'e'+'r' is computed
  2. a += result#1 is computed.

About 1.: this is the sum of two objects of type char, and it happends that their sum on your system is 1.

Finally, std::string::operator+= is invoked and is appended to your string.

What you really want is one of the following:

a += "er";
// or
a += 'e';
a += 'r';
// or
for (char c : your_char_array) {
    a += c;
}
// or
a += your_char_array;

1) If you were on an ASCII OS, as 'e' is 101 (decimal) and 'r' is 114 (decimal), their sum is 215 (decimal) which stands for 'Î' in extended ASCII.

YSC
  • 38,212
  • 9
  • 96
  • 149
  • Oh, I forgot that point! Thanks @YSC ! Is there any workaround for this to concatenate multiple char with String? – Aswin Jun 19 '18 at 17:23
-1

You are adding two characters which are numbers. 'e' + 'r' is computed first and since 'e' is 101 in ASCII and 'r' is 114 you are concatenating the character with the code 215. To concatenate "er":

string a = "den";
a += 'e';
a += 'r';
Alexandru Ica
  • 137
  • 2
  • 8
  • 1
    didnt downvote, though your answer fails to explain why `a += 'e';` works as expected while `a += 'e' + 'r';` does not. 'e' is 101 in ASCII no matter if you write `a += 'e';` or `a += 'e' + 'r';` – 463035818_is_not_an_ai Jun 19 '18 at 18:05