TheAsker
TheAsker

Reputation: 11

My code works now, but why? Adding '0' to a string

I've posted the relevant parts of the code I was working on below. At first, I was trying to add an integer to the end of a string.

However, none of the methods I found were working quite right (to_string, itoa, casting). Whenever I simply added the integer to the string, I would get the string plus an odd little symbol at the end, such as smiley face or spade. However, when I add a '0' to the line str += i, it works!

The problem is, I have no idea why. I was hoping someone would be willing to explain to me what exactly is going on here and why it works? I just don't understand how I can add integer to the string without a cast, and why adding a char (I think?) makes it work.

Thanks to everyone who takes the time to read this.

int main()
{
    string str = "Filler";
    int i = 2;       
    str += i+'0';      //if I remove the +'0' it no longer works as intended.
    cout << str << endl;
    return 0;

}

Upvotes: 0

Views: 225

Answers (2)

DomDom
DomDom

Reputation: 76

This is pure luck ;-)

Your code add i to the ascii value of '0' (=> 48).

In your sample 2+48 = 50 . And luckilly 50 is the ascii value for '2' so it works !!

If you try with 'a' instead of '0' (str += i+'a';) you will obtain a 'c' at the end of your string.

So, do not do that ;-)

The correct way to add an integer is discussed here :

How to concatenate a std::string and an int?

Good Luck !

Upvotes: 0

PhpLou
PhpLou

Reputation: 440

i+'0' here is adding the ASCII value of the character '0' to the value of i
i+'0' is equal to the ASCII code of the character '2'
so you are concatenating str to a number (at my computer it is 50) (which is different than 2 but this is the ASCII code for 2)
(note that 50 is based on my computer's ASCII table and might not be the same for you - I am not sure if it is unique for all)
and the character whose ASCII code is 2 is not '2', it is that odd character you got

Upvotes: 1

Related Questions