5

我目前正在做我的任务,必须使用 C-Free 5.0。只需要你的帮助来解决这个难题。我想为用户在到期前输入答案实施时间限制。我已经尝试过这段代码,但它在 scanf() 函数中被阻塞了。是否有任何其他方法,例如解锁输入或其他方法。我试图实现' #include <sys/select.h>'但这个程序没有那个库。

#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();
}
4

2 回答 2

1

这是一个示例程序,展示了如何在文件描述符上使用O_NONBLOCK标志。stdin

#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!");
}
于 2012-11-25T13:43:21.627 回答
0

由于您fcntl.h尝试将标准输入设置为非阻塞。它并不漂亮(主动等待),但如果你没有,select那么这是最简单的方法:

#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;
}

对您的代码的注释:if (st != NULL)将始终满足,因为st是堆栈指针。

于 2012-11-25T13:41:08.167 回答