Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input within a time limit in Standard C

Tags:

c

I'm currently doing my assignment and it's compulsory to use C-Free 5.0. Just need your help to solve this piece of puzzle. I want to implement a time limit for the user to input an answer before it expires. I've tried this code but it got block at scanf() function. Is there any other method like an unblocking input or something. I've tried to implement '#include <sys/select.h>' but this program doesn't have that library.

#include <stdio.h> 
#include <string.h>
#include <time.h>
#include <stdlib.h>

int main()
{
    char st[10];
    printf ("Please enter a line of text : ");
    time_t end = time(0) + 5; //5 seconds time limit.
    while(time(0) < end)
    {
        scanf("%s", &st);
        if(st != NULL)
        {
            printf ("Thank you, you entered >%s<\n", st);
            exit(0);
        }
    }
    main();
}
like image 217
Jazz Chin Avatar asked Nov 13 '22 16:11

Jazz Chin


1 Answers

Here is an example program that shows how you can use O_NONBLOCK flag on a stdin file descriptor.

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

#define INPUT_LEN 10

int main()
{
    printf ("Please enter a line of text : ");
    fflush(stdout);
    time_t end = time(0) + 5; //5 seconds time limit.

    int flags = fcntl(STDIN_FILENO, F_GETFL, 0);
    fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);

    char answer[INPUT_LEN];
    int pos = 0;
    while(time(0) < end)
    {
        int c = getchar();

        /* 10 is new line */
        if (c != EOF && c != 10 && pos < INPUT_LEN - 1)
            answer[pos++] = c;

        /* if new line entered we are ready */
        if (c == 10)
            break;
    }

    answer[pos] = '\0';

    if(pos > 0)
        printf("%s\n", answer);
    else
        puts("\nSorry, I got tired waiting for your input. Good bye!");
}
like image 161
Roman Byshko Avatar answered Nov 15 '22 06:11

Roman Byshko