C exit from infinite loop on keypress

前端 未结 5 972
囚心锁ツ
囚心锁ツ 2020-12-10 05:47

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.

5条回答
  •  离开以前
    2020-12-10 06:02

    // 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();
        }
    

提交回复
热议问题