How can I exit from an infinite loop, when a key is pressed? Currently I'm using getch, but it will start blocking my loop as soon, as there is no more input to read.
-
You used to be able to use `while(!kbhit())`, but this is prolly OS dependent. You might want to have a look at http://cboard.cprogramming.com/c-programming/63166-kbhit-linux.html, depending on your os – forsvarir Jul 18 '11 at 10:12
-
Check out GetAsyncKeyState Function if you are using Windows. – Juho Jul 18 '11 at 10:18
-
kbhit() may be OS-dependent, but it is declared in conio.h, just like getch(). So if he/she uses getch(), he/she should have kbhit() too. – Rudy Velthuis Jul 18 '11 at 10:59
4 Answers
If you are using getch()
from conio.h
anyway, try to use kbhit()
instead. Note that both getch()
and kbhit()
- conio.h
, in fact - are not standard C.

- 45,586
- 12
- 116
- 142

- 28,387
- 5
- 46
- 94
-
Yes, conio.h is not standard because they are dependent on the OS that is been used. – Talha Ahmed Khan Jul 18 '11 at 10:20
-
1Not every implementation of C has a conio.h at all, although many try to provide one, these days. How or if they are implemented depends on the platform, indeed. – Rudy Velthuis Jul 18 '11 at 10:24
The function kbhit()
from conio.h
returns non-zero value if any key is pressed but it does not block like getch()
. Now, this is obviously not standard. But as you are already using getch()
from conio.h
, I think your compiler has this.
if (kbhit()) {
// keyboard pressed
}
From Wikipedia,
conio.h is a C header file used in old MS-DOS compilers to create text user interfaces. It is not described in The C Programming Language book, and it is not part of the C standard library, ISO C nor is it required by POSIX.
Most C compilers that target DOS, Windows 3.x, Phar Lap, DOSX, OS/2, or Win321 have this header and supply the associated library functions in the default C library. Most C compilers that target UNIX and Linux do not have this header and do not supply the library functions.
If you do not want to use non-standard, non-blocking way and yet graceful exit. Use signals and Ctrl+C with user provided signal handler to clean up. Something like this:
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
/* Signal Handler for SIGINT */
void sigint_handler(int sig_num)
{
/* Reset handler to catch SIGINT next time.
Refer http://en.cppreference.com/w/c/program/signal */
printf("\n User provided signal handler for Ctrl+C \n");
/* Do a graceful cleanup of the program like: free memory/resources/etc and exit */
exit(0);
}
int main ()
{
signal(SIGINT, sigint_handler);
/* Infinite loop */
while(1)
{
printf("Inside program logic loop\n");
}
return 0;
}

- 2,887
- 5
- 25
- 40
// Include stdlib.h to execute exit function
int char ch;
int i;
clrscr();
void main(){
printf("Print 1 to 5 again and again");
while(1){
for(i=1;i<=5;i++)
printf("\n%d",i);
ch=getch();
if(ch=='Q')// Q for Quit
exit(0);
}//while loop ends here
getch();
}

- 11
- 1