我只是想知道是否可能以及如何实现此功能,如果没有用户输入,我们将退出循环。例如,如果用户在 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();
}
Use 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, NULL, &timeout))
{
scanf("%d", &x);
printf("The number you put is %d\r\n",x);
}
else
{
printf("\r\nTimeout: Stop reading\r\n");
break;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)