Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain the " - '0' " [duplicate]

Tags:

c++

arrays

string

 #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?

like image 473
yoshi105 Avatar asked Dec 11 '22 16:12

yoshi105


1 Answers

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.

like image 198
Ivaylo Strandjev Avatar answered Dec 29 '22 14:12

Ivaylo Strandjev