Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <cs50.h>
- #include <math.h>
- #include <string.h>
- int c2i(char c);
- int add_digits(int n);
- int LuhnsAlg(string CCnumber);
- int main(void)
- {
- string CCnumber; // declare string called CCnumber
- int CCNumberLengh; // declare int called CCNumberLengh
- do
- {
- CCnumber = get_string("Please enter a CC number: ");
- CCNumberLengh = strlen(CCnumber);
- }
- while (CCNumberLengh == 0 || CCnumber[0] > 57);
- if (CCNumberLengh < 15 || CCNumberLengh > 16)
- {
- printf("INVALID\n");
- return 0;
- }
- // Check starting numbers of credit cards & return VISA, AMEX or MASTERCARD
- // Verify CC is American Express. AA cards start with 34 or 37. Their card lengh can be 15 digits long
- if ((CCNumberLengh == 15) && c2i(CCnumber[0]) == 3 && (c2i(CCnumber[1]) == 4 || c2i(CCnumber[1]) == 7))
- {
- if (LuhnsAlg(CCnumber) == 0)
- {
- printf("AMEX\n");
- }
- else
- {
- printf("INVALID\n");
- }
- }
- // Verify CC is Mastercard. MC's start with a 51, 52, 53, 54 or 55. Their card lengh can be 16 digits long
- else if ((CCNumberLengh == 16) && (c2i(CCnumber[0]) == 5 || c2i(CCnumber[0]) == 2) && c2i(CCnumber[1]) >= 1 && c2i(CCnumber[1]) <= 5)
- {
- if (LuhnsAlg(CCnumber) == 0)
- {
- printf("MASTERCARD\n");
- }
- else
- {
- printf("INVALID\n");
- }
- }
- // Verify CC is visa. VISA's start with a 4. Their card lengh can be 13 OR 16 digits long
- else if ((CCNumberLengh == 13 || CCNumberLengh == 16) && CCnumber[0] == '4')
- {
- if (LuhnsAlg(CCnumber) == 0)
- {
- printf("VISA\n");
- }
- else
- {
- printf("INVALID\n");
- }
- }
- else
- {
- printf("INVALID\n");
- }
- }
- int add_digits(int n) // how this modulo works to add two digits together and why its needed for luhn's is in OneNote docco
- {
- int d = 0;
- while (n > 0)
- {
- d = d + n % 10;
- n = n / 10;
- }
- return d;
- }
- int c2i(char c) // to convert char to int you need to subtract a 48 based offset on the ascii table
- {
- return c - (int)('0');
- }
- int LuhnsAlg(string CCnumber) // detailed notes on how this function & forloops work are in your OneNote docco
- {
- int i = 0;
- int s = 0;
- int t = 0;
- for (i = strlen(CCnumber) - 2; i >= 0; i -= 2)
- {
- t = c2i(CCnumber[i]);
- s = s + add_digits(t * 2);
- }
- for (i = strlen(CCnumber) - 1; i >= 0; i -= 2)
- {
- t = c2i(CCnumber[i]);
- s = s + t;
- }
- if (s % 10 == 0) // If the total of the last digit of this card leftover is 0, card is valid
- {
- return 0;
- }
- else
- {
- return 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement