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

den*_*tic 0 c++ for-loop

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

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

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

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

Rak*_*ish 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).
    }
}
Run Code Online (Sandbox Code Playgroud)

要么

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