Search code examples
cstringstrtol

Extract numbers from string doesnt work! c


i would remove the "-" from the ISBN String. But my code dont print me the value out. Where is the fault?

char *ISBN[20];  //example: 3-423-62167-2
*p = ISBN;

strcpy(ISBN, ptr); //Copy from a Buffer
printf("\nISBN Array: %s", ISBN); //This works!

while(*p)
{
    if (isdigit(*p))
    {
        long val = strtol(p, &p, 10);
        printf("%ld\n", val);         //Do not show anything!
    }
    else
    {
        p++;
    }
}

Solution

  • Incorrectly using strtol is unnecessary; the 2nd argument is not an input, but an output i.e. it sets it to the last interpreted character. Above all, why do you want to convert the character to a long and then convert it back again to a character, when all you need is a character to print?

    char ISBN[] = "3-423-62167-2";
    char *p = ISBN;
    while (*p)
    {
        if (isdigit(*p))
            printf("%c", *p);
        ++p;
    }
    

    EDIT:

    To make the whole string into a long:

    unsigned long long num = 0;
    while (*p)
    {
        if (isdigit(*p))
        {
            const char digit = *p - '0';
            num = (num * 10) + digit;
        }
        ++p;
    }