虽然循环不会在C ++中破坏

时间:2012-10-04 12:38:26

标签: c++ while-loop

嘿我用C ++制作游戏。它的大学工作和简短的状态没有使用头文件和游戏必须是基本的。问题是,在游戏结束后仍然要求选择。我试图打破,退出,仍然没有快乐。该计划不会退出。 任何人都可以帮我这个吗?

这是我的代码: 主

int main()          //  The main function is set to int.  
    //  The return value has to be an integer value.
{
    menuText();
    while(menu)     // Loop to revert back to menu when choice is not compatable with options.
    {
        int selection;
        cout<< "Choice: ";
        cin>> selection;

        switch(selection)
        {
        case 1: 
            cout << "Start Game\n";
            playGame();
            break;
        case 2:
            cout << "Exit Game\n";
            cout << "Please press enter to exit...\n";
            menu = false ;
            break;
        }
    }


    system("pause");    //  To stop the program from exiting prematurely.
    return 0;           //  this is needed because the main is set to return
    //  an integer.
}

int playgame()
status Status = {100,20,80,80,20};// declaration of class members.
    //Contents of PlayGame().............................
    exitGame();
    return 0;
}
void exitGame()
{
    cout << "\n\nPlease press enter to exit the game.";
    return;

}

2 个答案:

答案 0 :(得分:2)

你基本上是这样做的:

int playGame()
{
    return 0;
}

int main(){
    bool menu = true;
    while(menu){
        cout<< "Choice: ";
        cin>> selection;

        switch(selection)
        {
        case 1: 
            cout << "Start Game\n";
            playGame();
            break; // This break symbolizes that you want to end switch statement
                   // not the whole loop
        }
    }
    return 0;
}

您可以这样做:

#define GAME_COMPLETED -1 /* Will close the game */
#define GAME_RESERVER 0

if( playGame() == GAME_COMPLETED){
    menu = false;
}

// And of course at the end of the playGame:
return GAME_COMPLETED;

您确定不想使用case '1':代替case 1:吗?

答案 1 :(得分:1)

我可能会误解你,但从我的理解 - 你希望游戏在playGame()功能完成后结束(如果我错了,请纠正我)。

为此,您只需在此块中设置menu=false; - 或者作为替代方案 - 从此案例中删除break;语句。这将使流程“落入”退出案例。