使用switch语句执行do-while循环-无限循环错误

时间:2018-09-28 17:33:44

标签: c++

我只是试图创建一个简单的“菜单”。基本上,用户可以输入他们的选择,当他们输入“ E”时,它应该退出菜单。我无法理解为什么它给了我无限循环-我知道它很可能是我的while循环(?)。它只是硬编码为即时消息,只是试图获得其要旨。

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main() 
{
    char choice;
    int numOfCups;

    cout << "Hot Beverage Menu: \n";
    cout << "A: Coffee $1.00 \n";
    cout << "B: Tea $0.75 \n";
    cout << "C: Hot Chocolate: $1.25 \n";
    cout << "D: Cappuccino: $2.50 \n";
    cout << "E: Exit Menu \n";

    cout << "Please make a drink selection:";
    cin >> choice;
    do {
        switch(choice) {
            case 'A': cout << "You chose Coffee \n";
            cout << "How many cups would you like?";
            cin >> numOfCups;
            cout << "Your total will be: " << '$' << fixed << setprecision(2) << (1.00 * numOfCups) << endl;
            cout << "Please make another selection:";
            cin >> choice;
            break;

            case 'B': cout << "You chose Tea \n";
            cout << "How many cups would you like? \n";
            cin >> numOfCups;
            cout << "Your total will be: \n" << '$' << fixed << setprecision(2) << (0.75 * numOfCups) << endl;
            cout << "Please make another selection:";
            cin >> choice;
            break;

            case 'C': cout << "You chose Hot Chocolate \n";
            cout << "How many cups would you like? \n";
            cin >> numOfCups;
            cout << "Your total will be: \n" << '$' << fixed << setprecision(2) << (1.25 * numOfCups) << endl;
            cout << "Please make another selection:";
            cin >> choice;
            break;

            case 'D': cout << "You chose Cappuccino \n";
            cout << "How many cups would you like? \n";
            cin >> numOfCups;
            cout << "Your total will be: \n" << '$' << fixed << setprecision(2) << (2.50 * numOfCups) << endl;
            cout << "Please make another selection:";
            cin >> choice;
            break;

            case 'E': cout << "Exit Menu";
            break;

            default: cout << "Invalid input. Please make another selection.";
            break;
        } 
    } while (choice == 'E');
        return 0;
}

2 个答案:

答案 0 :(得分:3)

只要条件为真,循环就会继续,如果条件为假,循环就会结束。您应该拥有while (choice == 'E')而不是while (choice != 'E')

此外,您应该将cin >> choice;添加到默认条件,否则在这种情况下将出现无限循环。

答案 1 :(得分:1)

尝试do ... while (choice != 'E');