How To Break an Infinite Loop with Key Press
Hi! :) Today, we will discuss on how to break a while loop using any key press in C++. So, first of all, we need to include the iostream header file for the program to accept inputs from the keyboard.
#include <iostream>
Here's the trick. Actually, I've read plenty ways on how to stop or break infinite loops or while loops in C++ and here is what I found that is the easiest and shortest. You can use the function _kbhit(). It is actually not a predefined function of C or C++ but is used by the Borland's family of compilers. It returns a non-zero integer if a key is in the keyboard buffer (Source: Cprogramming.com). So, we will be including the <conio.h> header file.
#include <iostream>
#include <conio.h>
The loop structure is up to you but here is mine. The loop will infinitely and endlessly loop until you enter any key.
void main () {
while (!_kbhit()) {
std:: cout << "Press enter key to break
loop :)" << std:: endl;
}
}
That's it! You made it :) So, here's the whole code :)
#include <iostream>
#include <conio.h>
#include <conio.h>
void main () {
while (!_kbhit()) {
std:: cout << "Press enter key to break
loop :)" << std:: endl;
}
}
For Enter Key
#include <iostream>
#include <conio.h>
void loop() {
while (!_kbhit()) {#include <conio.h>
void loop() {
std:: cout << "Press enter key to break
loop :)" << std:: endl;
}
}
void main () {
char ch = 0;
while (ch != 13) {
loop();
ch = _getch();
}
}
Note: the _getch() gets the character you entered from _kbhit().