Input within a time limit in Standard C

后端 未结 2 1948
野性不改
野性不改 2021-01-13 23:18

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 t

相关标签:
2条回答
  • 2021-01-13 23:55

    Since you have fcntl.h try setting stdin to non-blocking. It's not pretty (active waiting), but if you do not have select then this is the easyest way to go:

    #include <stdio.h> 
    #include <string.h>
    #include <time.h>
    #include <stdlib.h>
    #include <fcntl.h>
    #include <errno.h>
    
    int main()
    {
        // get stdin flags
        int flags = fcntl(0, F_GETFL, 0);
        if (flags == -1) {
            // fcntl unsupported
            perror("fcntl");
            return -1;
        }
    
        // set stdin to non-blocking
        flags |= O_NONBLOCK;
        if(fcntl(0, F_SETFL, flags) == -1) {
            // fcntl unsupported
            perror("fcntl");
            return -1;
        }
    
        char st[1024] = {0}; // initialize the first character in the buffer, this is generally good practice
        printf ("Please enter a line of text : ");
        time_t end = time(0) + 5; //5 seconds time limit.
    
        // while
        while(time(0) < end  // not timed out
            && scanf("%s", st) < 1 // not read a word
            && errno == EAGAIN); // no error, but would block
    
        if (st[0]) // if the buffer contains something
            printf ("Thank you, you entered >%s<\n", st);
    
        return 0;
    }
    

    A remark to your code: if (st != NULL) will always be satisfied since st is a stack pointer.

    0 讨论(0)
  • 2021-01-14 00:11

    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!");
    }
    
    0 讨论(0)
提交回复
热议问题