簡體   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