How to validate credit card numbers in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <algorithm> // for std::reverse
#include <cctype>    // for std::isdigit

/*
    Validate credit card numbers using the Luhn algorithm.
    ------------------------------------------------------
    The Luhn algorithm works as follows:

    1. Starting from the rightmost digit (the check digit), move left.
    2. Double every second digit.
    3. If doubling produces a number > 9, subtract 9.
    4. Sum all digits.
    5. If the total sum % 10 == 0 → the number is valid.

    This program:
    - Cleans input
    - Ensures all characters are digits
    - Applies the Luhn algorithm
    - Prints whether the card number is valid
*/


// ------------------------------------------------------------
// Remove spaces and hyphens from the input (common formatting)
// ------------------------------------------------------------
std::string cleanInput(const std::string& raw) {
    std::string cleaned;
    cleaned.reserve(raw.size());

    for (char c : raw) {
        if (std::isdigit(static_cast<unsigned char>(c))) {
            cleaned.push_back(c);
        }
    }
    return cleaned;
}


// ------------------------------------------------------------
// Check if the cleaned number is valid using the Luhn algorithm
// ------------------------------------------------------------
bool isValidLuhn(const std::string& number) {
    int sum = 0;
    bool doubleDigit = false;

    // Traverse digits from right to left
    for (auto it = number.rbegin(); it != number.rend(); ++it) {
        int digit = *it - '0';

        if (doubleDigit) {
            digit *= 2;
            if (digit > 9) digit -= 9;
        }

        sum += digit;
        doubleDigit = !doubleDigit;
    }

    return (sum % 10 == 0);
}


// ------------------------------------------------------------
// Main program
// ------------------------------------------------------------
int main() {
    std::string input = "4539 1488 0343 6467";

    std::string cleaned = cleanInput(input);

    if (cleaned.empty()) {
        std::cout << "Invalid input: no digits found.\n";
        return 0;
    }

    bool valid = isValidLuhn(cleaned);

    std::cout << "Cleaned number: " << cleaned << "\n";
    std::cout << "Result: " << (valid ? "VALID" : "INVALID") << "\n";
}


/*
run:

Cleaned number: 4539148803436467
Result: VALID

*/

 



answered Jul 15 by avibootz
...