What is the best way to terminate a while loop by pressing a specific key in C++?
Asked
Active
Viewed 654 times
-4
-
What you mean is a loop with exit condition (press key), and this is by definition not infinite loop. – Non-maskable Interrupt Aug 19 '15 at 15:14
2 Answers
1
Use system signal but you will not be able to stop with all keys.
#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;
}

Anis Belaid
- 304
- 2
- 8
0
You can quit the program, but there is no real way to make it stop with any key on a basic level.
Alternatively you can use another condition for the loop, e.g.
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
}

MisterC
- 239
- 1
- 5