Need help defining an infinite loop

This is a simplified version of my code:

void calc(char *s)
{
    int t = 0;
    while (*s)
    {
        if (isdigit(*s))
            t += *s - '0';
        else
            ++s;
    }
    printf("t = %d\n", t);
}

int main(int argc, char* argv[])
{
    calc("8+9-10+11");
    return 0;
}

The problem is that the while loop works forever, although I expect it to stop after the last digit 1. And my expected result: t = 20.

+3
source share
3 answers

sdoes not increase if it *sis a number, consider removing the else clause by entering the code in this:

while (*s)
{
    if (isdigit(*s))
        t += *s - '0';

    ++s;
}
+12
source

@Hasturkun gave you the correct answer, but this is what a debugger can help you if you have one available. Go through the code and you will quickly see that it does not execute the line ++s;.

+3
source

else

if (isdigit (* s))

t + = * s - '0';

 s++;
0

Source: https://habr.com/ru/post/1775165/


All Articles