### char to int

Hello!

I am using a book to study from and I was wondering how exactly this line of code works:

 result = (number[0] + number[1] + number[2] + number[3] + number[4] -4*'0');

specifically

 + number[4] -4*'0'

 ``1234567891011121314151617181920212223242526272829`` ``````#include using namespace std; int main() { char number[5], word[5], ch; int result, result2; cout << "Enter a 4-digit number:"; cin >> number; cout << int(char(2)); result = (number[0] + number[1] + number[2] + number[3] + number[4] -4*'0'); cout << "\Sum of digits =" << result; cout << "\nEnter a 4-letter word:"; cin >> word; ch = (word[0] + word[1] + word[2] + word[3]) / 4; cout << "\nAverage char =" << ch << endl; system( "pause"); return 0; }``````
http://www.asciitable.com/

What is the decimal value for 0?
There are several errors in that code.
This line:
 `` `` ``result = (number[0] + number[1] + number[2] + number[3] + number[4] -4*'0');``
 `` `` ``result = (number[0] + number[1] + number[2] + number[3] - 4*'0');``

The reason for the `- 4*'0'` is that the line is a simplification of this:
 ``1234`` `````` result = number[0] - '0' + number[1] - '0' + number[2] - '0' + number[3] - '0';``````

Also I think this line:
 `` `` `` cout << int(char(2));``
would make more sense and be more useful in the context, written like this:
 `` `` `` cout << int('2');``

At line 16, `"\Sum of digits ="` should be `"\nSum of digits ="`
Topic archived. No new replies allowed.