64,647
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
int flag=0;
void func(int p)
{
flag=1;
}
int get_number()
{
int num, def=1234;
puts("Input a number.");
struct sigaction act, oact;
act.sa_handler = func;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
act.sa_flags |= SA_INTERRUPT;
sigaction(SIGALRM, &act, &oact);
alarm(5);
scanf("%d", &num);
if (flag)
return def;
return num;
}
int main()
{
int choice;
choice = get_number();
printf("Your choice is %d\n", choice);
if (flag)
puts("It's the default choice.");
}
#include <conio.h>
int time_out=5; //5 seconds
int main()
{
time_out+=time(NULL);
cout<<"Input a choice [a,b,c]:"<<endl;
char ch;
while(true)
{
if (kbhit())
{
ch=getche();
printf("\n");
if (ch!='a'&&ch!='b'&&ch!='c')
{
cout<<"Wrong choice, try again [a,b,c]:"<<endl;
continue;
}
else
{
break;
}
}
if (time(NULL)>time_out)
{
cout<<"Time out, use default choice."<<endl;
ch='c';
break;
}
}
cout<<"Your have choosed "<<ch<<endl;
}