/* Copyright 2007 All Rights Reserved Paul Picazo (kinda) but he used a webpage to tell him what the Luhn method was and he also used his knowledge of programming from various courses and he also used a few google searches to see what the names of functions he was looking for were called. And to troubleshoot the itoa() not working when he compiled it on G++ on linux. References were not including because the information is so general that he could not figure out which of the many pages that contain the information he used initially. */ #include #include #include using namespace std; //takes in a string of numbers (with or without spaces) //returns true if it is a valid 16 digit credit card number //returns false if it has non numerical characters (after removing spaces) //returns false if it is not 16 digits in length (after removing spaces) //returns false if the number fails the luhn test, bad CC number bool checkCC(string input); //takes in int and returns string string itos(int x); //removes the spaces from a given string //returns the input string without spaces string removeSpaces(string input); int main() { string userInput; printf("Enter Credit Card Number:"); getline(cin, userInput); if(checkCC(userInput)) { printf("Credit Card: %s is good.\n", userInput.c_str()); } else { printf("Credit Card: %s is bad.\n", userInput.c_str()); } return 0; } bool checkCC(string input) { bool retVal = false; string temp = removeSpaces(input); if(temp.length() == 16) { retVal = true; for(int i = 0; i < 16; i++) { if(temp[i] > '9' || temp[i] < '0') { retVal = false; } } if(retVal == true) { for(int i = 14; i >= 0; i = i - 2) { char tempcharstar[3]; tempcharstar[0] = temp[i]; tempcharstar[1] = '\0'; int tdigit = atoi(tempcharstar); string tempdigit = ""; tempdigit = itos(tdigit * 2); temp.replace(i,1,tempdigit); } int sum = 0; for(int i = 0; i < temp.length(); i++) { char tempcharstar[2]; tempcharstar[0] = temp[i]; tempcharstar[1] = '\0'; int tdigit = atoi(tempcharstar); sum += tdigit; } if(sum % 10 == 0) { retVal = true; } else { retVal = false; } } else { //it is still gonna be false, no need to set it to false } } else { retVal = false; } return retVal; } string itos(int x) { ostringstream retVal; retVal << x; return retVal.str(); } string removeSpaces(string input) { string temp = ""; int ws = 0; int start = 0; while((ws = input.find(" ",start)) >= 0) { temp += input.substr(start, ws - start); start = ws + 1; } if(start + 1 < input.length()) temp += input.substr(start, input.length() - start); return temp; }