C++ Homework

I am trying to make a program to determine if a credit card is valid or not. I have got the program done but there is a logic error somewhere in my program. I have been trying to figure it out for what feels like forever now, any help would be appreciated. If you do not know how to verify a credit card here are the steps:

a) Double every second digit from right to left. If doubling of a digit results in a two-digit number, add
the two digits to get a single digit number.

b) Now add all single-digit numbers from Step a).
4 + 4 + 8 + 2 + 3 + 1 + 7 + 8 = 37

c) Add all digits in the odd places from right to left in the card number.
6 + 6 + 0 + 8 + 0 + 7 + 8 + 3 = 38

d) Sum the results from Step b) and Step c).
37 + 38 = 75

e) If the result from Step (d) is divisible by 10, the card number is valid; otherwise, it is invalid.

d) the first number must also be 4, 5, 6, or the first two numbers must be 37

For example, the number 4388576018402626 is invalid, but the number 4388576018410707 is valid.


#include <iostream>
#include <string>
using namespace std;

bool isValid(const string &);
int sumOfDoubleEvenPlace(const string &);
int getDigit(int);
int sumOfOddPlace(const string &);
bool startWith(const string &);

int main()
{
	string cardnumber;
	cout << "Enter a credit card number: ";
	getline(cin, cardnumber);

	cout << "The card number " << cardnumber << " is ";

	if (isValid(cardnumber))
		cout << "valid." << endl;
	else
		cout << "invalid." << endl;

	return 0;
}
// Return true if the card number is valid
bool isValid(const string& cardNumber)
{
	if (cardNumber.size() >= 13 && cardNumber.size() <= 16  && (sumOfDoubleEvenPlace(cardNumber) + sumOfOddPlace(cardNumber)) % 10 == 0 
		&& startWith(cardNumber))
		return true;
	else
		return false;
}

// Get the result from Step b
int sumOfDoubleEvenPlace(const string& cardNumber)
{
	int sum = 0;
	for (int i = cardNumber.size() - 2; i >= 0; i -= 2)
	{
		sum += int(getDigit(cardNumber[i]) * 2);
	}
	return sum;
}

// Return this number if it is a single digit, otherwise
// return the sum of two digits
int getDigit(int number)
{
	if (number <= 9)
		return number;
	else
		return (number / 10) + (number % 10);
}

// Return sum of odd-place digit in the card number
int sumOfOddPlace(const string& cardNumber)
{
	int sum = 0;
	for (int j = cardNumber.size() - 1; j >= 0; j -= 2)
	{
		sum += int(cardNumber[j]);
	}
	return sum;
}

// Return true if substr is the prefix for card number
bool startWith(const string& cardNumber)
{
	if (cardNumber[0] == '4' || cardNumber[0] == '5' || cardNumber[0] == '6' ||
		cardNumber[0] == '3' && cardNumber[1] == '7')
		return true;
	else
		return false;
}
Last edited on
> sum += int(getDigit(cardNumber[i]) * 2);
You seem to be passing '0' to '9' (the characters), not 0 to 9 (the integers).

Perhaps
 
sum += int(getDigit(cardNumber[i]-'0') * 2);
Last edited on
Topic archived. No new replies allowed.