Ahmed Yasen Ahmed Yasen - 11 months ago 56
C Question

atoi function doesn't work in for loop

I am trying to get the output of this equation :


44 - 10 + 11 / 5


it work properly as follow :

char str[] = "44 - 10 + 11 / 5";
int sum = 0 ;
sum += atoi(str); // 0 + 44
sum += atoi(str+3); // 44 + 10
sum += atoi(str+5); // 54 + 11
sum += atoi(str+7); // 65 / 5 = 13
printf("%d/n",sum); // output = 13


but it doesn't work if I put the
atoi()
function in the
for
loop:

char str[] = "44 - 10 + 11 / 5";
int sum = 0;
int i;
sum += atoi(str);
for (i = 0; i < 100; i++) {
if (!(str[i] >= 0 && str[i] <= 9)) { //if str[i] is not a number
sum += atoi(str + i);
}
}
printf("%d/n", sum); // output = 0

Answer Source

You are comparing a char value that contains the ASCII representation of a number, to an actual number. Change

if(!(str[i]>=0 && str[i]<=9)){  

to

if(!(str[i]>='0' && str[i]<='9')){  

I did not check if the rest of the code is correct, but certainly, this is one issue.