2

嘿,我正在为我的 C++ 编程课程制作一个 Switch 选择菜单。我已经设法让我的菜单工作,但我不知道如何在我制作的菜单中的退出选择上停止程序。

我的代码是

#include <iostream>
using namespace std;

int main()
{
    char selection;

    do
    {
        cout << "  IHCC Computer Science Registration Menu\n";
        cout << "  ====================================\n";
        cout << "  1.  Welcome to Computer Programming In C++\n";
        cout << "  2.  Welcome to Java Programming\n";
        cout << "  3.  Welcome to Android Programming\n";
        cout << "  4.  Welcome to iOS Programming\n";
        cout << "\n";
        cout << "  5.  Exit\n";
        cout << "  ====================================\n";
        cout << "  Enter your selection: ";
        cin >> selection;
        cout << endl;

        switch (selection)
        {
            case '1':
                cout << "Computer Programming In C++\n";
                cout << "\n";
                break;

            case '2':
                cout << "Java Programming\n";
                cout << "\n";
                break;
            case '3':
                cout << "Android Programming\n" ;
                cout << "\n";
                break;

            case '4':
                cout << "iOS Programming\n";
                cout << "\n";
                break;

            case '5':
                cout << "Goodbye.\n";
                break;

            default: cout <<selection << "is not a valid menu item.\n";

                cout << endl;
        }

    }while (selection != 0 );

    return 0;
}
4

3 回答 3

6

改变

while (selection != 0)

至:

while (selection != '5')

另请注意,您当前的方法仅读取单个字符。如果您不希望具有更多数字的数字根据第一个数字调用选择,请int改为阅读:

int selection = 0;

do {

    cout << ...        
    cin >> selection;

    switch (selection) {
        case 1:
            ...
            break;
        ...
        case 5:
            cout << "Goodbye.\n";
            break;

        default:
            ...
    }

} while (selection != 5);
于 2013-10-02T21:12:09.637 回答
2

LihO 和 sharth 有适当的解决方案,但是如果他们的想法是在输入 5 时退出程序,那么我建议对这种情况执行此操作:

case '5':
  cout << "Goodbye.\n";
  return 0;

它使程序退出那里,而不是稍后在代码中。

于 2013-10-02T21:14:33.180 回答
0

只需设置selection变量以满足您已经必须退出循环的条件:

case '5':
    cout << "Goodbye.\n";
    selection = 0;
    break;
于 2016-06-10T06:12:33.727 回答