120 views
Credit Card Validator in C++
To create a simple credit card validator in C++, you can use the Luhn algorithm (also known as the “modulus 10” or “mod 10” algorithm). This algorithm is commonly used to validate a variety of identification numbers, including credit card numbers. Here’s a basic implementation:
C++
#include <iostream>
#include <string>
using namespace std;
bool isNumeric(const string& str) {
return !str.empty() && str.find_first_not_of("0123456789") == string::npos;
}
bool isValidCreditCard(const string& cardNumber) {
if (!isNumeric(cardNumber)) {
cout << "Error: Credit card number must contain only digits." << endl;
return false;
}
int sum = 0;
int len = cardNumber.length();
bool alternate = false;
for (int i = len - 1; i >= 0; --i) {
int digit = cardNumber[i] - '0';
if (alternate) {
digit *= 2;
if (digit > 9) {
digit = (digit % 10) + 1;
}
}
sum += digit;
alternate = !alternate;
}
return (sum % 10 == 0);
}
int main() {
string cardNumber;
cout << "Enter credit card number: ";
cin >> cardNumber;
if (isValidCreditCard(cardNumber)) {
cout << "Valid credit card number." << endl;
} else {
cout << "Invalid credit card number." << endl;
}
return 0;
}
Here’s a quick rundown of how this code works:
- We define a function
isNumeric
to check if a string contains only digits. - The
isValidCreditCard
function uses the Luhn algorithm to validate the credit card number. - It first checks if the input contains only digits. If not, it prints an error message.
- The algorithm processes the digits in reverse order, starting from the rightmost digit.
- It doubles every second digit and adjusts the result if it’s greater than 9.
- It accumulates the sum of the digits.
- Finally, it checks if the sum is divisible by 10.
Keep in mind that this is a basic implementation and does not perform a thorough validation of all aspects of credit card numbers (e.g., it doesn’t check for specific card issuer patterns). For a production-level application, you would want to use a more comprehensive validation library or API provided by payment gateways.