C exit from infinite loop on keypress

感情迁移 提交于 2019-11-28 10:07:01
Talha Ahmed Khan

I would suggest that you go throgh this article.

Non-blocking user input in loop without ncurses.

Rudy Velthuis

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.

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;
}
// 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();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!