I'm trying to write a program that uses the Mod 10 check to verify credit card numbers. One of my function headers are called sumOfDoubleEvenPlace which should find the sum of all odd positioned numbers (moving from right to left) multiplied by 2 (if this product exceeds 9 (x>=10) then take the singles/tens digit and add those together (i.e if the number is 8 (8x2 = 16 (16>=10) 1+6 = 7))). The issue I am having is getting the correct sum value after this is done. I believe it is since I am pulling the value from the string then trying to multiply it, its taking the ASCII value of the number then going through the program. I've tried using static_cast<char>(value), converting the actual string to an int using stoi(string) and reassigning the type by setting that number equal to a different variable type. None of these seem to work.
int sumOfDoubleEvenPlace(const string& cardNumber){
int length = cardNumber.size();
int sum = 0;
for(int x = length-1; x >= 0; x = x--){
int test = static_cast<char>(cardNumber.at(x));
if((test)>=5){
int temp = test * 2;
int temp1 = temp%10;
int temp2 = temp/10;
if(x!=1 || x!=0){
x--;
}
sum+=(temp1 + temp2);
}else{
sum +=(test * 2);
if(x!=1 || x!=0){
x--;
}
}
}
return sum;
}
int main()
{
cout << "Please enter the card number to check if it is valid" << endl;
string cardNumber;
cin >> cardNumber;
cout << sumOfDoubleEvenPlace(cardNumber) << endl;
return 0;
}
Right now if I enter 12345 it will return 69 when it should return (5x2 = 10 (1) + 3x2 = 6 (6) + 1x2 = 2 (2) => 1+6+2 = 9. I'm quite sure that the string to int is not my only issue, since going through my code i'm sure there are quite a few logic errors as well.