2013-10-24 114 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