When running my program through cs50's submit50 check, everything works besides validating 4222222222222
as VISA
(instead of INVALID
) is output. When I print out the count variable before, then sometimes VISA
is output. Any solutions would be much appreciated as I cannot seem to properly fix this.
INSTRUCTIONS: Write a program that prompts the user for a credit card number and then reports (via
printf
) whether it is a valid American Express, MasterCard, or Visa card number, per the definitions of each’s format herein. So that we can automate some tests of your code, we ask that your program’s last line of output beAMEX\n
orMASTERCARD\n
orVISA\n
orINVALID\n
, nothing more, nothing less
#include <stdio.h>
#include <cs50.h>
int main(void)
{
//get input from user
long CardNum = get_long("Input credit card number:");
bool nvalid = true;
//count number of digits
int count = 0;
long temp1num = CardNum;
while (temp1num > 0)
{
temp1num = temp1num / 10;
count++;
}
//printf("%i\n", count);
if (!(count == 13 || count == 15 || count == 16))
{
printf("INVALID\n");
}
else
{
.....
The problem arises in the beginning of the code so I only copied that part.
Mastercards always starts with either 5 or 2 and has a length of 16.
Visa cards always start with a 4 and can have a length of 13-16-19.
You are close. Try adding an additional condition for the supported lengths for VISA in your if statement it should solve your problem. Or, why not just check if the card length is either 13 - 19? It seems like it's failing because Visa supports different card lengths.
I have an awesome helper method that determines card types that's extremely handy but it's in C#.