2013-10-24 176 views
2

我在這裏有一個代碼,可能會延遲10秒才能繼續,但我想添加一個功能,用戶可以等待延遲或按任意鍵繼續,我知道它不會像delay(10000) || getch();任何方式做到這一點?「按任意鍵或等待10秒鐘繼續」

#include <stdio.h> 
#include <conio.h> 
#include <dos.h> 

void main(){ 
    clrscr(); 
    printf("Press Any Key or Wait for 10 Seconds to Continue"); 
    delay(10000); 
    //getch(); 
} 
+2

你可以很好地與線程做到這一點。你對這個知道多少? – Bathsheba

+0

你可以採取一個時間戳,做一個忙等待循環,當一個鍵被按下或一個新的時間戳顯示10s已經通過 – Leeor

+0

結束[如何停用輸入語句一段時間?](http://stackoverflow.com/questions/18289635/how-to-deactivate-input-statement-after-some-time) – alk

回答

2
#include <stdio.h> 
#include <conio.h> 
#include <dos.h> 

void main() 
{ 
    int wait = 10000; 

    clrscr(); 
    printf("Press Any Key or Wait for 10 Seconds to Continue\n"); 

    while(!kbhit() && wait > 0) 
    { 
     delay(100); 
     wait -= 100; 
    } 
} 
+0

http://cboard.cprogramming.com/c-programming/63166-kbhit如果你需要的話,-linux.html爲linix提供'_kbhit'的實現。 – AShelly

+4

不是很便攜。 – alk

+0

@alk先生,「便攜式」這個術語對我來說是新的嗎?如果我使用這個「非常便攜」的代碼有什麼缺點? – 707

2

它的實際使用alarm很簡單:

printf("Press Any Key or Wait for 10 Seconds to Continue"); 
alarm(10); 
getch(); 
alarm(0); 

您可能需要設置一個處理器上SIGALRM雖然。

+0

請參閱我對OP的評論,以獲得使用此方法的完整示例的鏈接。 – alk