【问题标题】:C++: How can I make an infinite loop stop when pressing any key? [closed]C ++:按任意键时如何使无限循环停止? [关闭]
【发布时间】:2023-03-13 08:13:02
【问题描述】:

在 C++ 中按特定键终止 while 循环的最佳方法是什么?

【问题讨论】:

  • 你的意思是一个带有退出条件的循环(按键),根据定义,这不是无限循环。

标签: c++ loops infinite-loop infinite


【解决方案1】:

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

#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;
}

【讨论】:

    【解决方案2】:

    您可以退出程序,但没有真正的方法可以通过基本级别的任何键使其停止。

    或者,您可以为循环使用另一个条件,例如

    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-22
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      相关资源
      最近更新 更多