2

からいくつかの異なる数値を合計する必要があり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;
}

負の数を除いてすべてを完全に処理し、 を無視し-て 10 を加算します。

これを修正する方法を知っている人はいますか?私はそれを理解することができません。

4

2 に答える 2

6

if 条件を次のように変更します。

if (isdigit(*totaal) || (*totaal=='-'))

strtol負の数を処理できます。
例えばstrtol("-15",NULL,10)利回り-15

于 2014-05-28T15:14:30.157 に答える