如何在不中断的情况下提前结束循环

时间:2015-07-07 05:53:52

标签: c++ for-loop

for (int att = 1; att < 11; att++)
{
     <body>;
     //break will completely finish running the program
}

我正在制作一个CodeBreaker(Mastermind)游戏,而且我遇到的问题是在比一个小于11的需要时更早结束循环,然后将循环设置回att的初始化状态= 1。

att代表&#34;尝试&#34;。用户可以猜测随机生成的代码最多10次。一旦用户在少于10次尝试中猜到正确的代码,我想提示用户再次播放并生成新的随机代码。但是上面显示的循环仍在运行。

如何提前结束循环,但仍然继续运行程序?程序的大部分取决于这一个循环,因此break将完全阻止它运行。

5 个答案:

答案 0 :(得分:6)

set the loop back to the initialization state of att = 1,您可以使用continue

for (int att = 1; att < 11; att++)
{
    if(you_want_to_set_loop_back) {
        att = 1;
        continue;    //It will begin the loop back with att=1, but if any other variable is modified, they will remain as it is (modified).
    }
}

或者

您可以在函数中编写循环,其中包含您想要的所有变量的初始值。并且只要你愿意,就继续调用这个函数。要打破循环,使用break并从函数返回或直接从循环返回而不是破坏它。

答案 1 :(得分:3)

您可以执行以下操作:

while(true){
    for (int att = 1; att < 11; att++)
    {
        <body>;
        //game, and when it finishes
        break;
    }
    //Asks player if he wants to continue, if not then break again
}

答案 2 :(得分:1)

围绕for循环的while循环怎么样?

while(programRunning){
    for (int att = 1; att < 11; att++)
    {
        <body>;
        if(answer==correct){
            att = 12; // ends the for-loop
        }
    }
    if(gameOver){
        programRunning = false; // unless you want to end the game, starts the for-loop from att = 1
    }
}

答案 3 :(得分:1)

我想你可以尝试以下方式:

bool bQuitGame = false;
while(!bQuitGame)
{
    for(att = 1; att < 10; ++att)
    {
        if(you want to only quit "for" but stay in "while")
        {
            <code...>
            break;
        }
        else if(you want to quit "while")
        {
            <code...>
            bQuitGame = true;
            break
        }
        else if(you want to start the next iteration in "for")
        {
            <code..>
            continue;
        }
        else //you want to stay in "for"
        {
            <code...>
        }
    }
}

答案 4 :(得分:0)

看起来您的问题可以通过这样的简单嵌套循环来解决:

while(!success){
    for (int att = 1; att < 11; att++){
        <body>;
        if(answer is correct){
            success = true;
            break;
        }
        //break will completely finish running the program

    }
}
相关问题