Search code examples
ccharintegerintstrtol

Summing up numbers from a char* in C


I need to sum up some different numbers from a char*.

The char is something like "12,38,40" where the result is 90, but it can also be "12/5?10,-20" where the result should be 7.

The code I already have is:

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;
}

It handles everything perfectly except the negative numbers, it just ignores the - and adds the 10.

Does anybody know how to fix this? I can't get my head around it.


Solution

  • Change your if condition to:

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

    strtol is capable of handling negative numbers.
    e.g. strtol("-15",NULL,10) yields -15.