C ++:按任意键时如何进行无限循环停止?

时间:2015-08-19 15:05:04

标签: c++ loops infinite-loop infinite

我对编程很陌生,我不知道其他主题是怎么说的。有人请在C ++上完整解释。

2 个答案:

答案 0 :(得分:0)

使用系统信号但您无法使用所有按键停止。

#include <iostream>
#include <csignal>

using namespace std;

void signalHandler( int signum )
{
    cout << "Interrupt signal (" << signum << ") received.\n";

    // cleanup and close up stuff here  
    // terminate program  

   exit(signum);  

}

int main ()
{
    // register signal SIGINT and signal handler  
    signal(SIGINT, signalHandler);  

    while(1){
       cout << "Going to sleep...." << endl;
       sleep(1);
    }

    return 0;
}

答案 1 :(得分:0)

您可以退出该程序,但没有真正的方法可以让它在基本级别上使用任何键停止。

或者你可以使用另一个条件进行循环,例如

int counter = 0;
int counterMax = 100;
while (true && (counter++ < counterMax)) {
    // your code here
}
if (counter >= counterMax) {
    std::cout << "loop terminated by counter" << std::endl;
    // maybe exit the program
}