如果没有输入,则在一定时间后退出循环
发布时间:2020-12-16 05:02:26 所属栏目:百科 来源:网络整理
导读:我只是想知道是否可能以及如何实现此功能,如果没有来自用户的输入,我们将退出循环.例如,如果用户在1分钟后没有输入任何内容,我想退出循环.这是我的C代码: #include stdio.h#include conio.h#include time.hint main(void){ int x; time_t end = time(0) + 6
我只是想知道是否可能以及如何实现此功能,如果没有来自用户的输入,我们将退出循环.例如,如果用户在1分钟后没有输入任何内容,我想退出循环.这是我的C代码:
#include <stdio.h> #include <conio.h> #include <time.h> int main(void) { int x; time_t end = time(0) + 60; printf("Enter a number : "); while (time(0) < end) { if((scanf("%d",&x)) != EOF || (getchar() != 'n')) { time_t end2 = time(0) + 60; while(time(0) < end2); main(); } else { printf("%d",x); main(); } } main(); } 解决方法
使用select()函数为scanf设置超时
以下代码是如何使用它的示例. #include <stdlib.h> #include <stdio.h> #include <sys/time.h> int main(void) { int x; fd_set set; struct timeval timeout = {0}; FD_ZERO(&set); while(1) { timeout.tv_sec = 30; FD_SET(fileno( stdin ),&set); printf ("enter a number:"); fflush (stdout); if (select(FD_SETSIZE,&set,NULL,&timeout)) { scanf("%d",&x); printf("The number you put is %drn",x); } else { printf("rnTimeout: Stop readingrn"); break; } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |