2014-07-24 75 views
0

我的程序應該要求用戶輸入他們的信用卡號碼,然後顯示數字是否有效或無效,如果有效,顯示卡的類型。我在嘗試讀取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; 
} 
+5

臨提示:你會發現,如果你正確地格式化,更容易調試代碼。 –

+2

關於'cardNumber.length()> = 13 && cardNumber.length()> = 16'的條件。如果長度等於或大於16,那麼它肯定等於或大於13。 –

+0

好的,所以有很多概念,你必須清楚你的方法。如果你打算使用C++,那麼有更好的方法來編碼。 –

回答

1

你的代碼有一些奇怪的部分,但問題是你正在測試第一位數字而數字存儲在一個字符串中。所以測試應該是if (cardNumber.at(0) == '4') ...

1

你的一個問題是,你得到的第一個字符(在0位置),並把它比作一個int。字符的值(整數)是字符在當前編碼中的值。例如,在ASCII encoding(這是最常見的)中,字符'4'的值爲52

所以這就是爲什麼比較cardNumber.at(0)==4將失敗,因爲4不等於'4'

1
if (cardNumber[0] == '4') { 
    // VISA 
} else if (cardNumber[0] == '5') { 
    // mastercard 
} else if (cardNumber[0] == '6') { 
    // discover 
} else if (cardNumber[0] == '3' && cardNumber[1] == '7') { 
    // American Express 
} else { 
    // Invalid card type 
} 

順便說一句,你的卡號長度驗證條件是不是你期望的,它應該是什麼

if (cardNumber.length() >= 13 && cardNumber.length() <= 16) {...}