-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcc-validator.cpp
More file actions
44 lines (34 loc) · 1.05 KB
/
cc-validator.cpp
File metadata and controls
44 lines (34 loc) · 1.05 KB
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
#include <iostream>
#include <string>
//#include <cstdio>
// Luhn Algorithm
bool checkLuhn(const std::string& cardNo) {
int nDigits = cardNo.length();
int nSum = 0, isSecond = false;
for(int i = nDigits - 1; i >= 0; i--) {
int d = cardNo[i] - '0';
if(isSecond == true)
d = d * 2;
nSum += d / 10;
nSum += d % 10;
isSecond = !isSecond;
}
return (nSum % 10 == 0);
}
// User Input and Validation
int main() {
std::cout << "Please enter the card number:" << std::endl;
std::string cardNo;
std::cin >> cardNo;
if(checkLuhn(cardNo)) {
std::cout << "This is a valid card number." << std::endl;
} else {
std::cout << "This is not a valid card number." << std::endl;
}
std::cin.get();
std::cout << "--------------------------------------------------" << std::endl;
std::cout << "Press ENTER to exit the program." << std::endl;
std::cin.get();
// Or using C -> std::getchar();
return 0;
}