总结来自C中的char*的数字

Zen*_*ipu 2 c int integer char strtol

我需要总结一些不同的数字char*.

char类似于"12,38,40"结果为90的位置,但也可以是"12/5?10,-20"结果为7的位置.

我已经拥有的代码是:

extern int Add()
{
    char *string = "ab230c,i d*(s370*(20k-100d";
    char *totaal = string;

    int Sum = 0;

    while (*totaal)
    {
        if (isdigit(*totaal)) 
        {
            int getal = strtol(totaal, &totaal, 10);
            printf("%ld\n", getal);

            if(getal >= 0)
            {
                Sum += getal;
            }
        }
        else 
        {
            totaal++;
        }
    }
    printf("the sum of all numbers is: %d\n", Sum);
    return Sum;
}
Run Code Online (Sandbox Code Playgroud)

除负数之外,它完全处理所有事情,它只是忽略-并添加10.

有人知道如何解决这个问题吗?我无法理解它.

ani*_*ane 6

将您的if条件更改为:

if (isdigit(*totaal) || (*totaal=='-'))
Run Code Online (Sandbox Code Playgroud)

strtol能够处理负数.
例如strtol("-15",NULL,10)收益率-15.