forked from Aditya-devp/Contributershub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Credit Card Validator.cpp
62 lines (42 loc) · 1.36 KB
/
Credit Card Validator.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
bool isNumberString(const string& s) {
int len = s.length();
for (int i = 0; i < len; i++) {
if (s[i] < '0' || s[i] > '9')
return false;
}
return true;
}
int main() {
string ccNumber;
cout << "This program uses the Luhn Algorigthm to validate a CC number." << endl;
cout << "You can enter 'exit' anytime to quit." << endl;
while (true) {
cout << "Please enter a CC number to validate: ";
cin >> ccNumber;
if (ccNumber == "exit")
break;
else if (!isNumberString(ccNumber)) {
cout << "Bad input! ";
continue;
}
int len = ccNumber.length();
int doubleEvenSum = 0;
for (int i = len - 2; i >= 0; i = i - 2) {
int dbl = ((ccNumber[i] - 48) * 2);
if (dbl > 9) {
dbl = (dbl / 10) + (dbl % 10);
}
doubleEvenSum += dbl;
}
for (int i = len - 1; i >= 0; i = i - 2) {
doubleEvenSum += (ccNumber[i] - 48);
}
cout << (doubleEvenSum % 10 == 0 ? "Valid!" : "Invalid!") << endl;
continue;
}
return 0;
}