我的程序應該要求用戶輸入他們的信用卡號碼,然後顯示數字是否有效或無效,如果有效,顯示卡的類型。我在嘗試讀取cardNumber字符串中的前兩個字符時遇到問題,以便查明卡類型是簽證,萬事達卡,美國運通還是發現(簽證4張,萬事達卡5張,美國運通卡37張,美國運通卡3張,探索)需要幫助閱讀字符串中的字符
#include <iostream>
#include <string>
using namespace std;
int main()
{
string cardNumber; //this will carry the number given by the user.
int sum(0), sumOfDoubleEven(0), sumOfOdd(0), evenDigit(0), oddDigit(0);
cout << "This program is the Credit Card Number Validator." << endl;
cout << "This program will check the validity status of your card number" << endl;
//Main loop
do
{
cout << endl << "Please provide a number to validate or type 'n' to quit ";
cin >> cardNumber; //gets cardNumber from user
if(cardNumber.length()>=13 && cardNumber.length()>=16)
{
if (cardNumber == "n") break; //exits loop on user request
//this for loop repeats once for each digit of the cardNumber.
//digitPosition decrements by one on each pass from last position to first position
for (int digitPosition=cardNumber.length(); digitPosition>0; digitPosition--)
{
if (digitPosition%2 == 0)
{ //executes the following code if digitPosition is even
oddDigit=(int)cardNumber[digitPosition-1]-'0';
sumOfOdd=sumOfOdd+oddDigit;
} else { //executes the following code if digitPosition is odd.
evenDigit=((int)cardNumber[digitPosition-1]-'0')*2;
evenDigit=evenDigit%10+evenDigit/10;
sumOfDoubleEven=sumOfDoubleEven + evenDigit;
}
}
sum=sumOfOdd+sumOfDoubleEven; //sums the result
cout << endl <<"The number "<<cardNumber<<" you provided is ";
if (sum%10==0) //executes if sum is divisible by 10
cout << "valid" << endl;
else //executes if sum is not divisible by 10
cout << "invalid" << endl;
if(cardNumber.at(0)==4) {
cout<<"Your Card type is VISA"<<endl;
} else {
cout<<"Sorry, you've entered a card number not in the range of 13-16 digits" <<endl;
}
}
}while (cardNumber != "n");
return 0;
}
臨提示:你會發現,如果你正確地格式化,更容易調試代碼。 –
關於'cardNumber.length()> = 13 && cardNumber.length()> = 16'的條件。如果長度等於或大於16,那麼它肯定等於或大於13。 –
好的,所以有很多概念,你必須清楚你的方法。如果你打算使用C++,那麼有更好的方法來編碼。 –