1

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?

4
  • 2
    What did you expect and why do you think your resultis weird? word[i+1] didn't throw error because out-of-bound check is not performed there. Try word.at(i+1) instead. Commented Jul 8, 2020 at 14:09
  • Okay that makes sense I thought it would automatically check for out of bounds( Java did so from my admittedly spotty memory of it). That clears that up, do you know why it is resulting in such high numbers though? I thought it would have something to do with the ascii values of it however that didn't seem to be it as the value of numbers is the same as their int values. (IE Ascii Value of 1 is 1) Commented Jul 8, 2020 at 14:14
  • 2
    ASCII value of 1 is not 1 but 49. Commented Jul 8, 2020 at 14:15
  • Oh okay I must have misread the chart then, that explains the values I was getting then, thank you for the answer! Commented Jul 8, 2020 at 14:19

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Not std::vector but std::string is used here.
The program is not ill-formed, it has undefined behavior.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.