0

I'm working on a code to verify valid credit card numbers. I'll be using the Luhn algorithm logic eventually, But first I'm trying to store the single digits of the card number into an array of size 20. Since there is no way to split an integer (integer here is the credit card number) I thought of getting the remainder of the integer by dividing by 10 (This way I can get the individual digits). However, my problem is that when the size of the integer becomes 11 or more, only a few digits are getting stored and with the wrong values. I just started to learn C programming and would really appreciate it if someone could help me, Thank you.

Note: I have given -1 to the 0th index of the array to say that it's the end of the card number. eg: 123467321234-1

Code :

#include <stdio.h>

int main() {
    long int cardNo[20];
    long int input_cardNo;
    int cardNo[0] = -1;                                //card number ends here
    int i = 1;

    printf("Enter your card number : ");
    scanf("%d", &input_cardNo);

    do {
        long int remainder = input_cardNo % 10;        //getting the remainder of card number
        long int division  = input_cardNo / 10;        //getting the div value of card number
        cardNo[i] = remainder;                         //assigning the remainder value to an [i] index in the array
        printf("%d\n", cardNo[i]);
        input_cardNo = division;                       //updating the card number with the div vale
        i++;
    } while (input_cardNo != 0);

    return 0;
}
Chris
  • 26,361
  • 5
  • 21
  • 42
  • 7
    Credit card "numbers" are not "numbers"; they are a series of digits. Get the input and deal with it as a "string" (whose elements are all ASCII digit characters.) You'll thank me later... – Fe2O3 Sep 09 '22 at 04:32
  • 2
    You should store credit card number as a string, because it is not a _number_, it's a string of numeric characters. It never makes sense to, for example, add two credit card numbers together or multiply them, which gives the hint that they are indeed strings. – hyde Sep 09 '22 at 04:33
  • 1
    @hyde One can, however, divide the "number" with a pair of scissors. `:-)` – Fe2O3 Sep 09 '22 at 04:38

1 Answers1

1

Just a brief explanation why long int does not work.

For most operating systems long int stores have the same capacity as int, it stores from -2^31 to 2^31 - 1. See: Long Vs. Int C/C++ - What's The Point?

With this, the maximum value is: 2147483648 or around 9-10 digits for your case. You may use long long int to store up to 4.611686e+18 or 17-18 digits.

  • You probably should mention what others have said in the comments, regarding credit card numbers not being numbers and instead, strings. – aulven Sep 13 '22 at 14:36