Whenever I input any card number into the program it outputs INVALID. I think the issue has something to do with not finding the first digits (int fdig) correctly because I used a print function before the fdig section and it printed in the output. I can't find any issues in the logic though, nothing I try works. Let me know if you see an issue in that section, or if you notice that something else is causing the problem. Thanks!
Here is the "check50" for reference:
:) credit.c exists
:) credit.c compiles
:( identifies 378282246310005 as AMEX expected "AMEX\n", not "INVALID\n"
:( identifies 371449635398431 as AMEX expected "AMEX\n", not "INVALID\n"
:( identifies 5555555555554444 as MASTERCARD expected "MASTERCARD\n", not "INVALID\n"
:( identifies 5105105105105100 as MASTERCARD expected "MASTERCARD\n", not "INVALID\n"
:( identifies 4111111111111111 as VISA expected "VISA\n", not "INVALID\n"
:( identifies 4012888888881881 as VISA expected "VISA\n", not "INVALID\n"
:( identifies 4222222222222 as VISA expected "VISA\n", not "INVALID\n"
:) identifies 1234567890 as INVALID
:) identifies 369421438430814 as INVALID
:) identifies 4062901840 as INVALID
:) identifies 5673598276138003 as INVALID
:) identifies 4111111111111113 as INVALID
:) identifies 4222222222223 as INVALID
#include <cs50.h>
#include <stdio.h>
int main(void)
{
//Asks the user for the card number
long number;
do
{
number = get_long("Number?\n");
}
while (number < 1 || number > 9999999999999999);
//Counts the digits the card has
int dcounter = 0;
while (number != 0)
{
number /= 10;
dcounter++;
}
//Verifies number is 13, 15, or 16 digitts
if (dcounter != 13 && dcounter != 15 && dcounter !=16)
{
printf("INVALID\n");
return 0;
}
//Luhn's Algorithm (found the do while loop online)
long card = number;
int acheck = 0;
int total = 0;
int s1 = 0;
int s2 = 0;
int m1;
int m2;
int d1;
int d2;
do
{
m1 = card % 10;
card = card / 10;
s1 = s1 + m1;
m2 = card % 10;
card = card / 10;
m2 = m2 * 2;
d1 = m2 % 10;
d2 = m2 /10;
s2 = s2 + d1 + d2;
}
while (card > 0);
total = (s1 + s2);
// Checks if passed luhn's algorithm
if (total % 10 != 0)
{
printf("INVALID\n");
return 0;
}
//Finds card's first digit and decide which type of card it is
int fdigs = number;
int visa = 0;
int mcard = 0;
int amex = 0;
do
{
fdigs = fdigs / 10;
}
while (fdigs > 100);
if (fdigs / 10 == 4)
{
visa = 1;
}
else if ((fdigs / 10 == 5) && (0 < fdigs % 10 && fdigs % 10 < 6))
{
mcard = 1;
}
else if ((fdigs / 10 == 3) && (fdigs % 10 == 4 || fdigs % 10 == 7))
{
amex = 1;
}
else
{
printf("INVALID\n");
return 0;
}
//Final Output
if (visa == 1 && mcard == 0)
{
printf("VISA\n");
}
else if (visa == 0 && mcard == 1)
{
printf("MASTERCARD\n");
}
else if (amex == 1)
{
printf("AMEX\n");
}
}