Home > Enterprise >  Continue code if user input isn't given C
Continue code if user input isn't given C

Time:11-02

My question is the following:

Is there a way to continue my code and skip the input if a certain time is passed

for example :

printf("How old are you");

int age;
scanf("%d",&age);
// I don't know how to check if the time has been exeeded
sleep(5)

if("Time exeeded"){
 printf("It's seems like the user is not there\n\n Goodbye");
 return 1;

}
else {
 printf("You are %d,age");
 return 0;
}

Thank you for your answers

CodePudding user response:

The typical solution is to use a timeout on select:

/* Set a 10 second timer on a scanf */

#include <unistd.h>
#include <stdio.h>
int
main(void)
{
    struct timeval tp = { .tv_sec = 10, .tv_usec = 0 };
    char b[32];
    fd_set fds;

    FD_ZERO(&fds);
    FD_SET(STDIN_FILENO, &fds);
    switch( select(STDIN_FILENO   1, &fds, NULL, NULL, &tp) ){
    case 1:
        if( FD_ISSET(STDIN_FILENO, &fds) ){
            if( scanf("1s", b) == 1 ){
                printf("Read: %s\n", b);
            }
        }
        break;
    case 0:
        puts("Timeout");
        break;
    default:
        fputs("Error\n", stderr);
    }
}
  • Related