【发布时间】:2011-08-29 05:55:18
【问题描述】:
我想制作一个要求输入用户名的代码,但时间限制为 15 秒。如果用户超过限制并且未能输入名称(或任何字符串),则代码将被终止并显示“超时”按摩,否则应保存名称并显示“谢谢”按摩。我曾尝试过这样的尝试,但这是错误的并且无法正常工作。请给我一个解决方案。谢谢。
#include <stdio.h>
#include <time.h>
int timeout ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
return 1;
}
int main ()
{
char name[20];
printf("Enter Username: (in 15 seconds)\n");
printf("Time start now!!!\n");
scanf("%s",name);
if( timeout(5) == 1 ){
printf("Time Out\n");
return 0;
}
printf("Thnaks\n");
return 0;
}
【问题讨论】:
-
建议使用:
getitimer()和setitimer()(可能只需要setitimer()函数。建议阅读setitimer()的MAN 页面 -
建议使用
select()函数,最后一个参数为struct timeval,内容为15秒