C++:按下任意键时,如何使无限循环停止? P>在C++中按下某个特定的键来终止while循环的最好方法是什么?< /p> < p>使用系统信号,但不能用所有的键停止。 #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; }
您可以退出该程序,但没有真正的方法使它停止与任何关键的基本水平 或者,您可以为循环使用另一个条件,例如C++:按下任意键时,如何使无限循环停止? P>在C++中按下某个特定的键来终止while循环的最好方法是什么?< /p> < p>使用系统信号,但不能用所有的键停止。 #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; },c++,loops,infinite-loop,infinite,C++,Loops,Infinite Loop,Infinite,您可以退出该程序,但没有真正的方法使它停止与任何关键的基本水平 或者,您可以为循环使用另一个条件,例如 int counter = 0; int counterMax = 100; while (true && (counter++ < counterMax)) { // your code here } if (counter >= counterMax) { std::cout << "loop terminated by counte
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
}
你的意思是一个有退出条件的循环,按定义这不是无限循环。