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

C++: How can I make an infinite loop stop when pressing any key?

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

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

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

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

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

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
}