2011-07-18 103 views
8

如何在按下按键时从无限循环退出? 目前我使用的是getch,但它会尽快阻止我的循环,因为没有更多的输入可供读取。C按键无限循环退出

+0

您以前可以使用'while(!kbhit())',但这是与操作系统相关的。您可能需要查看http://cboard.cprogramming.com/c-programming/63166-kbhit-linux.html,具体取决于您的操作系统 – forsvarir

+0

如果您使用的是Windows,请查看GetAsyncKeyState函数。 – Juho

+0

kbhit()可能依赖于操作系统,但它在conio.h中声明,就像getch()一样。所以如果他/她使用getch(),他/她也应该有kbhit()。 –

回答

4

无论如何,如果您使用的是getch(),您可以尝试使用kbhit()来代替conio.h。请注意这两个getch()kbhit() - conio.h,其实 - 如果任何键被按下,但它不会阻止像getch()不规范C.

+0

是的,conio.h不是标准的,因为它们依赖于使用的操作系统。 –

+1

并非C的所有实现都有conio.h,尽管现在很多人都试图提供一个conio.h。确实如何或如何实施取决于平台。 –

2

功能kbhit()conio.h返回非零值。现在,这显然不是标准。但是,因为你已经在使用getch()conio.h,我认为你的编译器有这个。

if (kbhit()) { 
    // keyboard pressed 
} 

Wikipedia从,

CONIO.H是在旧的MS-DOS的编译器用于创建文本用户界面的C头文件。它在C语言程序设计语言书中没有描述,它不是C标准库ISO C的一部分,也不是POSIX所要求的。

针对DOS,Windows 3.x,Phar Lap,DOSX,OS/2或Win32 1的大多数C编译器都有此标题,并在默认C库中提供了相关的库函数。大多数针对UNIX和Linux的C编译器都没有这个头文件,也没有提供库函数。

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

如果你不想使用非标准的,无阻塞的方式,但体面退出。使用信号和Ctrl + C与用户提供的信号处理程序进行清理。例如:

#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; 
}