Taking the CS50 course and need to make a program that, when putting in a credit card number, returns to you if that card is valid, and if that card is American Express, MasterCard, or Visa.
I've looked up multiple Stack Overflow discussions about this topic, mostly with incorporating Luhn's algorithm into C. I ended up compiling a program that, to me, seems fine and should run without any issues. However whenever I put in a credit card number, it always results as Invalid no matter if that card is valid or not.
I read multiple comments from other discussions about getting the CC number as a string, but decided to leave it as a long, mostly because that is what the instructions advise you to do
Could anyone please help me with identifying the issue in my code, this has been a painful process.
UPDATE: Changing "long" to "long long" seemed to work, and the program now works fine, but now when I enter a number from "valid" credit cards other than AMEX, MC, and Visa (e.g. a Discover card), my program doesn't print Invalid and just does nothing. Any suggestions on how to fix this?
#include <cs50.h>
#include <stdio.h>
// AMEX 34, 37; MASTERCARD 51, 52, 53, 54, 55; VISA 4
// 13, 15, or 16 digits
int main(void)
{
long number = get_long("Credit Card Number: ");
long cc = number;
int length = 0;
// Get length of number
while (cc > 0)
{
cc /= 10;
length++;
}
// Check if length is valid
if (length != 13 && length != 15 && length != 16)
{
printf("INVALID\n");
}
// Get first digits
long cc1 = number;
for (int x = 0; x < length - 2; x++)
{
cc1 /= 10;
}
int firsttwo = cc1;
int first = cc1 / 10;
// Checksum; Luhn Algorithm
long i = number;
int d;
int sum = 0;
while (i > 0)
{
d = i % 10;
sum += d;
i /= 100;
}
long y = number / 10;
int d2;
int prod = 0;
int sum2 = 0;
while (y > 0)
{
d2 = y % 10;
prod = d2 * 2;
if (prod >= 10)
{
prod = prod - 9;
}
sum2 += prod;
y /= 100;
}
int total = sum + sum2;
if (total % 10 != 0)
{
printf("INVALID\n");
}
if ((length == 13 || length == 16) && first == 4)
{
printf("VISA\n");
}
if(length == 15 && (firsttwo == 34 || firsttwo == 37))
{
printf("AMEX\n");
}
if(length == 16 && (50 < firsttwo && firsttwo < 56))
{
printf("MASTERCARD\n");
}
}