使用字符串的C++ Switch语句

2jcobegt  于 2023-02-26  发布在  其他
关注(0)|答案(1)|浏览(325)

我完全知道switch必须和int一起使用,但是我的任务要求我在用户输入字符串时使用switch。
我看过了,我看到一些提到 stoi,但我不确定这是否是我的教授所期望的,因为我们还没有被介绍过它。我是C++的新手,所以我还在学习,这段代码还没有完成,但我该怎么做呢?

int main()
{
    // Declare Constant variables
    const float DISC_GOLF_RETAIL = 14.96;
    const float ULTIMATE_RETAIL = 20.96;
    const double DISCOUNT1 = 8;
    const float DISCOUNT2 = .16;
    const float DISCOUNT3 = .24;
    const float DISCOUNT4 = .32;
    const double DEC = 100;

    // Declare variables
    double quantity;
    double pricePerDisc;
    double totalSavings;
    double total;
    char userInput;
    float discount;
    string discType;
    string disc1 = "Ultimate Disc";
    string disc2 = "Disc-Golf Disc";

    // Display title
    cout << "Welcome to the Flying-Disc Shop!" << "\n" << endl;

    // Prompt the user for input
    cout << "Enter 'u' for ultimate discs and 'g' for disc golf: ";
    cin >> (userInput);
    cout << endl;

    switch (discType)
    {
        case 1: userInput == 'u' || 'U';
            discType = disc1;
            pricePerDisc = ULTIMATE_RETAIL;
            break;

        case 2: userInput == 'g' || 'G';
            discType = disc2;
            pricePerDisc = DISC_GOLF_RETAIL;
            break;

        default:
            cout << "Invalid disc type." << endl;
            return 0;
    }

    cout << "Enter the number of Ultimate Disc(s): ";
    cin >> (quantity);
    cout << endl;

    cout << "------------Receipt------------" << endl;

    if (quantity > 5 && quantity <= 9)
    {
        discount = DISCOUNT1 / DEC;
        totalSavings = (pricePerDisc * quantity) * discount;
    }
    else if (quantity > 10 && quantity <= 19)
    {
        discount = DISCOUNT2;
        totalSavings = (pricePerDisc * quantity) * discount;
    }
    else if (quantity > 20 && quantity <= 29)
    {
        discount = DISCOUNT3;
        totalSavings = (pricePerDisc * quantity) * discount;
    }
    else if (quantity >= 30)
    {
        discount = DISCOUNT4;
    }

    totalSavings = (pricePerDisc * quantity) * discount;
    total = quantity * pricePerDisc - totalSavings;
    cout << "Disc Type: " << discType << endl;
    cout << "Quantity: " << quantity << endl;
    cout << "Pricer per Disc: " << "$ " << fixed << setprecision(2)
    << pricePerDisc << endl;
    cout << "Total Savings: " << "$ " << "-" << fixed << setprecision(2)
    << totalSavings << endl;
    cout << "Total: " << "$ " << total << fixed << setprecision(2) << endl;
}
vlju58qv

vlju58qv1#

对于单个 char 响应,可以使用switch/case语句:

switch (userInput)
{
    case 'g':
    case 'G': 
       /* ... */
       break;
    case 'u':
    case 'U': 
       // ...
       break;
    default:
       // ...
       break;
}

单个字符与字符串的处理方式不同。字符串通常由多个字符组成。

相关问题