离开了一定的时间后,循环,如果没有输入 [英] Exits the loop after a certain amount of time if there's no input
本文介绍了离开了一定的时间后,循环,如果没有输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是想知道是否有可能?如何实现此功能,我们从循环退出如果没有来自用户的输入。例如,我想退出循环,如果用户在1分钟后不输入任何东西。这里是我的C code:
的#include<&stdio.h中GT;
#包括LT&;&CONIO.H GT;
#包括LT&;&time.h中GT;INT主要(无效)
{
INT X;
time_t的结束时间=(0)+ 60;
的printf(请输入一个数字:); 而(时间(0)LT端)
{
如果((scanf函数(%d个,&安培;!x))= || EOF(getchar函数()='\\ n'))
{
time_t的END2 =时间(0)+ 60;
而(时间(0)LT; END2);
主要();
}
其他
{
的printf(%D,X);
主要();
}
}
主要();
}
解决方案
使用选择()
函数来设置超时为您scanf函数
以下code是如何使用它的例子。
的#include<&stdlib.h中GT;
#包括LT&;&stdio.h中GT;
#包括LT&; SYS / time.h中>INT主要(无效)
{
INT X;
FD_SET设置;
timeval结构超时= {0}; FD_ZERO(安培;设置);
而(1)
{
timeout.tv_sec = 30;
FD_SET(的fileno(标准输入),功放;套);
的printf(请输入一个数字:);
fflush(标准输出);
如果(选择(FD_SETSIZE,&安培;集,NULL,NULL,&安培;超时))
{ scanf函数(%d个,&安培; X);
的printf(你把号为%d \\ r \\ n,x)的; }
其他
{
的printf(\\ r \\ nTimeout:停止读\\ r \\ n);
打破;
}
}
}
I'm just wondering whether is it possible and how do I implement this feature, where we exit from the loop if there's no input from the user. For example, I want to exit the loop if the user does not input anything after 1 minute. Here's my C code :
#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();
}
解决方案
Use select()
function to set a timeout for your scanf
The following code is an example of how use it.
#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, NULL, &timeout))
{
scanf("%d", &x);
printf("The number you put is %d\r\n",x);
}
else
{
printf("\r\nTimeout: Stop reading\r\n");
break;
}
}
}
这篇关于离开了一定的时间后,循环,如果没有输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文