ryanquestioncsp
ryanquestioncsp

Reputation: 33

Addition Operation from ints in a String

I set up a string filled solely with numbers and using a for loop iterated through it in order to add them together mathematically (Wanted to see if the language would allow this), as a result I got some weird Numbers as the result. Can someone explain why this is happening?

int main()
{
std::string word = "2355412";
for (int i = 0; i<word.size(); i++){
    int sum = word[i]+word[i+1];

    std::cout << sum << std::endl;
}

return 0;
}

The code when run results in:

101
104
106
105
101
99
50

Due to the way I wrote my code I also believe that it should have resulted in an out of bounds error due word[i+1] on the final value resulting in the calling of a value that does not exist. Can someone explain why it did not throw an error?

Upvotes: 1

Views: 72

Answers (2)

Puck
Puck

Reputation: 2114

The value you get is not what you expect because it is the sum of the ascii code corresponding to the characters you are summing, it's not converted into their value by default.

Also, as mentioned by other, string::operator[] doesn't check if you are trying to reach an out of bound value. In this case, you read 0 because you reached the string termination character \0 which happen to be 0.

Upvotes: 1

Caleth
Caleth

Reputation: 62636

it should have resulted in an out of bounds error

string::operator[] doesn't check bounds, it assumes you have. If you call it with an out of bounds index, the entire behaviour of your program is undefined, i.e. anything can happen.

It sounds like you want string::at, which does check bounds, and will throw std::out_of_range

Upvotes: 1

Related Questions