#include <iostream> // cin, cout
using namespace std;
int main(void)
{
char c[80];
int i, sum=0;
cin.getline(c,80);
for(i=0; c[i]; i++) // c[i] != '\0'
if('0'<=c[i] && c[i]<='9') sum += c[i]-'0';
cout<< "Sum of digits = " << sum << endl;
getchar();
getchar();
return 0;
}
I understand everything accept for the sum += c[i] - '0'; i removed the "-'0'" and it didn't give me the correct answer. Why is this?
This converts a character from its character code(which is 48 in ASCII for instance) to its integer equivalent. Thus it turns the character '0'
to the value 0 as integer. As Pete Becker noted in a comment in the language definitions of both C and C++ it is required that all number characters are consecutive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With