【问题标题】:while loop multiple statementswhile循环多条语句
【发布时间】:2020-04-15 22:38:10
【问题描述】:

我有一些循环问题。我正在尝试循环多个语句。代码如下。

int MenuSelect () {
    cout << endl;
    cout << YELLOW  << "Enter 1 for info" << endl;
    cout << " " << endl;
    cout << "Enter 2 to Start" << endl;
    cout << " " << endl;
    cout << "Enter 3 to view settings" << endl;
    cout << " " << endl;
    cout << "Enter 4 to quit" << endl;

     int selected = 0;
    string input;
    cin >> input;
    if (stringstream(input) >> selected) {
        return selected;
    }
    else {
        return -1;
    }

    return 0;

};    

int Menu(int) {

    int selected {};
    while ((selected = MenuSelect()) == 1) {

        printmessage();


    }
    if (selected == 3) {

        cout << "Current Settings" << endl;

        somefunction();
    }

    else if (selected == 2) {

        cout << "Starting Game..... " << endl;
    }

    else if (selected == 4) {

        cout << "Exiting....." << endl;
        exit (3);
    }

    else {

        cout << "Invalid Entry" << endl;
        exit (3);
    }

    cout << "Below is the Deck of cards and you will get to choose 5 cards to play with. Choose wisely." << endl;

    return 0;

};

所以你可以看到用户可以看到菜单,然后 if 和 else 语句完成工作。目前我已经设法循环第一个菜单选择,所以如果用户输入 1 它将打印消息然后循环回菜单。我想要的是还循环 3 - 当前设置,如果用户输入无效数字。我试图完成它,但我似乎做不到。

【问题讨论】:

  • 将那些 if/else if 块移动到循环体中,然后将循环条件更改为 while ((selected = MenuSelect()) &gt; 0) (在这种情况下有效,因为您的 4 案例只调用 exit ),或者将selected = MenuSelect() 拉出循环并在循环体的末尾再次运行。
  • @0x5453 谢谢你解决了这个问题

标签: c++ loops while-loop


【解决方案1】:

您可能想要反复阅读用户输入并做出相应的反应?你可以把所有的ifs放到while

int Menu(int) {

    int selected {};
    bool loop = true;

    while (loop) {
        selected = MenuSelect();

        if(selected == 1) {
            printmessage();
        }
        else if (selected == 3) {
            cout << "Current Settings" << endl;

            somefunction();
        }
        else if (selected == 2) {
            cout << "Starting Game..... " << endl;
        }
        else if (selected == 4) {
            cout << "Exiting....." << endl;
            loop = false;
        }
        else {
            cout << "Invalid Entry" << endl;
            loop = false;
        }
    }

    cout << "Below is the Deck of cards and you will get to choose 5 cards to play with. Choose wisely." << endl;

    return 0;

};

使用变量loop退出while只是个人喜好,也可以无限循环

while(true)

并使用break; 退出循环或使用exit() 退出整个程序,就像现在一样。

【讨论】:

    猜你喜欢
    • 2011-10-23
    • 2018-05-27
    • 2015-05-19
    • 1970-01-01
    • 2019-11-07
    • 2013-06-09
    • 2013-12-20
    • 2014-01-21
    • 2015-11-08
    相关资源
    最近更新 更多