需要帮助从字符串中读取字符

时间:2014-07-24 15:13:22

标签: c++

我的程序应该要求用户输入他们的信用卡号码,然后显示这些号码是有效还是无效,如果有效,则显示卡片类型。我在尝试读取cardNumber字符串中的前2个字符时遇到问题,以便查明卡类型是签证,万事达卡,美国快递还是发现(4个用于签证,5个用于万事达卡,37个用于美国快递, 6发现)

#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;
}

3 个答案:

答案 0 :(得分:1)

您的一个问题是,您获得第一个字符(位置0)并将其与int进行比较。字符的值(整数)是字符在当前编码中的值。例如,在ASCII encoding(最常见)中,字符'4'的值为52

这就是比较cardNumber.at(0)==4失败的原因,因为4不等于'4'

答案 1 :(得分:1)

您的代码中有一些奇怪的部分,但问题是您在数字存储在字符串中时测试数字的第一个数字。所以测试应该是if (cardNumber.at(0) == '4') ...

答案 2 :(得分: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) {...}