繁体   English   中英

摆脱无限循环

[英]Breaking out of an infinite loop

有没有办法在不使用Ctrl + C的情况下打破无限循环? 我想在其他程序中实现这种方法。 像此示例程序中一样:

#include <iostream>

int main()
{
     int x = 0;
     for(;;)
         cout << x;
}

有没有办法让for循环继续进行,但随时用一些键将其中断。 我还应该解释一下我理解使用break ;,但我希望循环继续进行。 如果我使用这样的中断条件,for循环将停止并等待响应。

#include <iostream>

int main()
{
     int x = 0;
     for(;;)
     {
         cout << x;
         if(getch()=='n')
                break;
     }  

}

找到希望在遇到循环时打破循环的某些条件,然后使用break关键字:

#include <iostream>

int main()
{
     int x = 0;
     for(;;)
         cout << x;
         if(/* break condition*/){
             break;
         }
}

没有什么可以阻止您通过检测用户的特定键盘输入来实现中断条件的。

编辑:从您已编辑的问题看来,您想让循环一直持续运行并且不停止等待用户输入。 我能想到的唯一方法是产生一个新线程,以侦听用户输入,该用户输入会更改在主线程的中断条件下检测到的变量。

如果您可以访问c ++ 11和新的线程库,则可以执行以下操作:

#include <iostream>
#include <thread>

bool break_condition = false;

void looper(){
    for(;;){
        std::cout << "loop running" << std::endl;
        if(break_condition){
            break;
        }
    }
}

void user_input(){
    if(std::cin.get()=='n'){
        break_condition = true;
    }
}

int main(){
    //create a thread for the loop and one for listening for input
    std::thread loop_thread(looper);
    std::thread user_input_thread(user_input);

    //synchronize threads
    loop_thread.join();
    user_input_thread.join();

    std::cout << "loop successfully broken out of" << std::endl;
    return 0;
}

如果您决定采用线程方法,请多加注意,因为多线程代码中存在单线程代码中不存在的问题,有时它们确实很讨厌。

我认为您正在寻找继续

#include <iostream>

int main()
{
     int x = 0;
     for(;;)
     {
         cout << x;
         if(getch()=='n')
                continue;
     }  

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM