0

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

Luís Otávio
  • 183
  • 1
  • 13
  • I think it is better to use string (`char` array) for card number instead of numeric variable. Imagine that first 2 digits are 00. – i486 Aug 02 '20 at 13:56
  • I am using integer because in this particular problem the input never starts with 0 – Luís Otávio Aug 02 '20 at 14:09
  • In some cases the data looks like numeric but in fact is string even if all characters are digits. – i486 Aug 02 '20 at 14:44

1 Answers1

2

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')

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256