patterncModerate
Credit card verification: string conversion most optimal?
Viewed 0 times
conversionoptimalcreditcardstringmostverification
Problem
Below is some code which verifies a credit card number using the checksum as well as check if number of digits are appropriate as well if digits start with right numbers. I am not sure if converting the
Also, in my use of
double into a string was the best bet. I wasn't going to at first but had trouble figuring out the modulo math to get every second digit without knowing the length of the double (# of digits).Also, in my use of
strtok(), what should I be doing with the balance of the string after the delimiter? Is that hanging out in memory somewhere?#include
#include
#include
int main(void)
{
double cardnumber;
printf("Give me a number: \n");
scanf("%lf", &cardnumber);
if(cardnumber 10000000000000000)
{
printf("INVALID\n");
return 0;
}
if(cardnumber 9999999999999)
{
printf("INVALID\n");
return 0;
}
char creditcard[17];
sprintf(creditcard, "%f", cardnumber);
char* ptr_cc;
ptr_cc = strtok(creditcard,".");
int card_size = strlen(ptr_cc);
int sum = 0;
for(int i = 1; i =10)
{
prod = prod%10 + prod/prod%10;
}
sum += prod;
}
for(int i = 0; i ='1' && creditcard[1] <='5'))
{
printf("MASTERCARD\n");
return 0;
}
else
{
printf("INVALID\n");
return 0;
}
}Solution
As @Keith says, credit card numbers should be treated as strings, not numbers, and definitely not floating-point numbers. If you want to ensure that the input contains only digits (and maybe spaces), use
The Luhn checksum check should be in its own function. The loop indexes would be more natural counting down, I think, since you are taking every other digit starting from the right.
strspn(). Squeeze out any spaces, then validate the length using strlen().The Luhn checksum check should be in its own function. The loop indexes would be more natural counting down, I think, since you are taking every other digit starting from the right.
int is_valid_luhn(const char *creditcard)
{
int card_size = strlen(creditcard);
int sum = 0;
for(int i = card_size - 2; i >= 0; i -= 2)
{
int digit = creditcard[i] - '0';
int prod = 2 * digit;
sum += prod / 10 + prod % 10; /* No special case needed */
}
for(int i = card_size - 1; i >= 0; i -= 2)
{
sum += creditcard[i] - '0';
}
return sum % 10 == 0;
}Code Snippets
int is_valid_luhn(const char *creditcard)
{
int card_size = strlen(creditcard);
int sum = 0;
for(int i = card_size - 2; i >= 0; i -= 2)
{
int digit = creditcard[i] - '0';
int prod = 2 * digit;
sum += prod / 10 + prod % 10; /* No special case needed */
}
for(int i = card_size - 1; i >= 0; i -= 2)
{
sum += creditcard[i] - '0';
}
return sum % 10 == 0;
}Context
StackExchange Code Review Q#45455, answer score: 12
Revisions (0)
No revisions yet.