在标准C的时限内输入

我正在完成我的任务,并且必须使用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();
}

解决方法

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

#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!");
}

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...