开发者

Need help figuring out 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 with the while loop running forever, though I'm expecting it to stop after the final digit 1. And my expected output is t = 20.


s is not incremented if *s is a digit, consider removing the else clause, making the code into this:

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

    ++s;
}


@Hasturkun has given you the right answer, but this is the kind of a thing a debugger could help you with, if you have one available. Step through the code and you'd quickly see it's not executing the ++s; line.


your else condition is not fulfilled

try this

if (isdigit(*s))

t += *s - '0';

 s++;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜