我最近开始使用 C++ 并试图理解语法,但我遇到了放置问题。我必须做一个信用卡验证功能,要求提供一张有效的信用卡,然后我必须打印出信用卡的类型。
我唯一的问题是用于确定信用卡类型的 if 语句。我不知道它们的确切放置位置以及我是否缺少任何括号等。
对我来说有问题的确切块是:
if(c.substr(0, 2) == "65" || c.substr(0, 5) == "6011" || c.substr(0, 7) >= "622126" && c.substr(0, 7) <= "622925" || c.substr(0, 4) >= "644" && c.substr(0, 4) <= "649")
s = "You have a Discover card";
if(c.substr(0, 2) >= "51" && c.substr(0, 2) <= "55")
s = "You have a MasterCard card";
if(c.substr(0, 1) == "4")
s = "You have a Visa card";
if(c.substr(0, 2) == "34" || c.substr(0, 2) == "37")
s = "You have an American Express card";
这是我的代码。
#include <iostream>
#include <string>
using namespace std;
void validateCC();
string checkCC(string, int, bool&);
bool validateCCNum(string);
void main() {
char again;
cout << "Validate a credit card number (Y/N)? ";
cin >> again;
while (toupper(again) == 'Y') {
validateCC();
cout << "Validate a credit card number (Y/N)? ";
cin >> again;
}
}
void validateCC() {
string ccn, msg;
bool OK;
int ccLen;
cout << "Please enter a 15 or 16 digit credit card number."
<< "\n(No spaces or hyphens): ";
cin >> ccn;
ccLen = ccn.length();
msg = checkCC(ccn, ccLen, OK);
if(!OK)
cout << msg;
else
if(validateCCNum(ccn))
cout << "Valid credit card number\n";
else
cout << "Invalid credit card number\n";
cout << "\n" << endl;
}
string checkCC(string c, int cLen, bool& ccOK) {
string s = "";
ccOK = true;
for(int i=0;i<cLen && ccOK;++i)
ccOK = isdigit(c[i]);
if(c.substr(0, 2) == "65" || c.substr(0, 5) == "6011" || c.substr(0, 7) >= "622126" && c.substr(0, 7) <= "622925" || c.substr(0, 4) >= "644" && c.substr(0, 4) <= "649")
s = "You have a Discover card";
if(c.substr(0, 2) >= "51" && c.substr(0, 2) <= "55")
s = "You have a MasterCard card";
if(c.substr(0, 1) == "4")
s = "You have a Visa card";
if(c.substr(0, 2) == "34" || c.substr(0, 2) == "37")
s = "You have an American Express card";
if(ccOK == false) {
s = "Invalid credit card number digits";
} else if(cLen == 15) {
if(c.substr(0, 2) != "34" && c.substr(0, 2) != "37") {
ccOK = false;
s = "Invalid American Express credit card number";
}
} else if(cLen != 16) {
ccOK = false;
s = "Invalid credit card number length";
}
return s;
}
bool validateCCNum(string cc) {
bool flip = true;
int tmp, num = 0;
int ccLen = cc.length()-1;
for(int ndx=ccLen;ndx>=0;ndx--) {
if(flip)
num += cc[ndx] - '0';
else {
tmp = (cc[ndx] - '0') * 2;
if(tmp <= 9)
num += tmp;
else
num += (1 + (tmp - 10)); // max of 18
}
flip = !flip;
}
return num % 10 == 0;
}
我不知道有问题的块是否属于它当前所在的位置,或者我是否将它放在 validateCC() 部分中,然后为它添加一个参数。
谢谢你。