cstringstrtol

Strtol function returning wrong value


I need to get a credit card number as input on an exercise, to dos so I'm ussing the function fgets (getting it as a string to check if it is realy a number) and then strtol to make it a long integer. But the integer value return by the function does not match the one on the string.

while (*endptr != '\n') {
        char card_number_string[20];
        char *endptr;
        long int card_number;

        printf("Number: ");
        fgets(card_number_string, 20, stdin);
        card_number = strtol(card_number_string, &endptr, 10);
        printf("Result: %ld", card_number);
    }

For example, when I input the value 4003600000000014 the output of the strtol shown in the printf is 2147483647.

Is it a bug on my code? Or the function does return something different like this??

Note: All the variables are declared on top of the main function, they are in there just to know how they were declared


Solution

  • Value is outside long range. 2147483647 is the max value of long in your case.

    Use long long. (or unsigned long long if negative CC# are not needed)

        //long int card_number;
        long long card_number;
    
        printf("Number: ");
        fgets(card_number_string, 20, stdin);
        
        //card_number = strtol(card_number_string, &endptr, 10);
        card_number = strtoll(card_number_string, &endptr, 10);
    
        //printf("Result: %ld", card_number);
        printf("Result: %lld", card_number);
    

    Note: char *endptr; shadows the endptr in while (*endptr != '\n')