2011-07-18 104 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; 
}