首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >while循环多个语句

while循环多个语句
EN

Stack Overflow用户
提问于 2020-04-15 22:19:55
回答 1查看 42关注 0票数 0

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

代码语言:javascript
复制
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-当前设置,如果用户输入一个无效的数字。我试过了,但似乎做不到。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-15 22:38:11

您可能希望重复读取用户输入并做出相应的反应?您可以将所有的if放入while

代码语言:javascript
复制
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只是个人喜好,您可能会有一个无限的循环

代码语言:javascript
复制
while(true)

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61231102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档