c++ - 在从字符串中读取字符时需要帮助

标签 c++

我的程序应该要求用户输入他们的信用卡号码,然后显示号码是否有效,如果有效,则显示卡类型。我在尝试读取 cardNumber 字符串中的前 2 个字符以查明卡类型是 visa、mastercard、american express 还是 discover 时遇到问题(visa 为 4,mastercard 为 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;
}

最佳答案

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

关于c++ - 在从字符串中读取字符时需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24937601/

相关文章:

c++ - Openssl aes.h [链接器错误] undefined reference

c++ - 如何在 Cygwin 中将 speech.h 添加到 g++?

c++ - 为什么 OpenGL 不在这段代码中绘制多边形?

c++ - 在 QT 中重载 QDebug

c++ - 如何为 Qt 6 安装 websocket?

c++ - B 树中的指针

c++ - 未定义对 `__imp___glutInitWithExit' 等的引用,但库已链接

c++ - 通过 std::regex 从数学表达式制作树

c++ - 如何在 C++ 中为 Node.JS 实现动态变量

c++ - 我的 C++ OpenGL SDL 程序未按我的预期运行