- '0'
(or less portable - 48
, for ASCII only) is used to manually convert numerical characters to integers through their decimal codes, C++ (and C) guarantees consecutive digits in all encodings.
In EBCDIC, for example, the codes range from 240
for '0'
to 249
for '9'
, this will work fine with - '0'
, but will fail with - 48
). For this reason alone it's best to always use the - '0'
notation like you do.
For an ASCII example, if '1'
's ASCII code is 49
and '0'
's ASCII code is 48
, 49 - 48 = 1
, or in the recommended format '1' - '0' = 1
.
So, as you probably figured out by now, you can convert all the 10 digits from characters using this simple arithmetic, just subtracting '0'
and in the other direction you can convert all digits to it's character encoding by adding '0'
.
Beyond that there are some other issues in the code:
- The array does not start being populated at index
0
, but at index 1
, so if your string input is, for instance, "10"
the sum
will be a[1]
+ a[0]
, but a[0]
has no assigned value, so the behaviour is undefined, you need to wach out for these cases.
for (int i = 0; i < 5; i ++)
cin >> a[i];
would be more appropriate, indexes from 0
to 4
, since the array has 5 indexes, if you want input numbers from 1 to 5, you can subract 1
from the to the index later on.
- As pointed out in the comment section, a bad input, with alpabetic characters, for instance, will also invoke undefined behaviour.