#include
#include
using namespace std;
int isNumber(string temp)
{
// check whether the input is a
// 16-digit number by comparing the items
// in the string with the ascii values
// for numbers starting at 0:48 to 9:57
int tc;
for (int x =0; x=48 && tc <= 57) {
if (x==temp.length()-1) return 1;
}
else {
return 0;
}
}
}
int val(char ch)
{
// change char of a number to its int value.
// 0 in ascii starts at 48 hence the value in the return function.
int tc;
tc = ch;
return (tc-48);
}
int luhn (string temp)
{
// luhn algorithm or modulo 10.
// more info on wikipedia.
int sum,total,valtemp;
sum=0;
for (int x=0; x< temp.length();x++) {
if (x % 2 == 0) {
valtemp = val(temp[x]) *2;
if (valtemp > 9) valtemp -= 9;
} else {
valtemp = val(temp[x]);
}
sum += valtemp;
}
if (sum%10 == 0) {
//number is valid.
return 1;
} else {
//number is not valid
return 0;
}
}
int process(string temp)
{
// process user input
if (temp.length() < 16 || temp.length()> 16) {
cout << "Error: Please insert 16 digits." << endl;
} else {
if (isNumber(temp) == 1) {
cout<<"Calculating..." << endl;
if (luhn(temp)==1) {
cout << "Validated: Credit card number is valid." << endl;
} else {
cout << "Credit card number is not valid" << endl;
}
} else {
cout << "Only numbers are permitted." << endl;
}
}
return 0;
}
int main()
{
string temp;
//User Input.
cout << "Check credit card(16 digits):"<< endl;
cin >> temp;
process(temp);
return 0;
}