【发布时间】:2023-03-13 08:13:02
【问题描述】:
在 C++ 中按特定键终止 while 循环的最佳方法是什么?
【问题讨论】:
-
你的意思是一个带有退出条件的循环(按键),根据定义,这不是无限循环。
标签: c++ loops infinite-loop infinite
在 C++ 中按特定键终止 while 循环的最佳方法是什么?
【问题讨论】:
标签: c++ loops infinite-loop infinite
使用系统信号,但您无法使用所有键停止。
#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
}
【讨论】: