加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在标准C的时限内输入

发布时间:2020-12-16 07:02:24 所属栏目:百科 来源:网络整理
导读:我正在完成我的任务,并且必须使用C-Free 5.0.只需要你的帮助来解决这个难题.我想实现一个时间限制,让用户在到期前输入答案.我已经尝试过这段代码,但它在scanf()函数中遇到了阻塞.有没有其他方法,如解锁输入或其他东西.我试图实现’#include sys / select.h‘
我正在完成我的任务,并且必须使用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] = '';

    if(pos > 0)
        printf("%sn",answer);
    else
        puts("nSorry,I got tired waiting for your input. Good bye!");
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读