从内循环c ++内部突破外循环

Cod*_*de0 1 c++ loops break

(我知道有关于此的多个线程,但是在连续搜索5分钟后我无法找到使用C或C++的线程)

我想问一下如何在内循环内部突破外环.

例:

while (true) {
    for (int i = 0; i < 2; i++) {
        std::cout << "Say What?";
        // Insert outer-loop break statement here
    }
}
Run Code Online (Sandbox Code Playgroud)

以上只是一些伪代码.不要担心逻辑.

Bla*_*pel 7

将循环放在函数中并从中返回.

void RunMyLoop (...)
{
    while (true)
    {
        for (int i = 0; i < 2; i++)
        {
            std::cout << "Say What?";
            if (SomethingHappened)
                return;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

可以用goto.

while (bKeepGoing)
{
    for (int i = 0; i < 2; i++)
    {
        std::cout << "Say What?";
        if (EventOccured)
        {
            goto labelEndLoop;
        }
    }
}
labelEndLoop:
//...
Run Code Online (Sandbox Code Playgroud)

你也可以使用一个布尔值,以"破"了.

bool bKeepGoing = true;
while (bKeepGoing)
{
    for (int i = 0; i < 2; i++)
    {
        std::cout << "Say What?";
        if (EventOccured)
        {
            bKeepGoing = false;
            break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)