c - C语言如何在不停止程序的情况下使用scanf?

标签 c input counter

我正在做一个计数器,显示用户必须进行输入的秒数。问题是当我使用 scanf() 时,程序将停止并等待答案,但我不希望这样。即使用户没有输入任何内容,我也想继续运行计数器。

例子:

for(int i=10;i>=0;i--){
            i==0? printf("time over\n"):printf("%d seconds left\n",i);
            scanf("%s", decision);
            sleep(1);
        }

我该怎么做才能解决这个问题?

最佳答案

如评论中所述,一种可能性是使用轮询。

man poll 说:

poll() examines a set of file descriptors to see if some of them are ready for I/O or if certain events have occurred on them.

在代码中它可能是这样的:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/poll.h>
#include <stdbool.h>

int main() {
    struct pollfd fds[1];
    fds[0].fd = STDIN_FILENO;
    fds[0].events = POLLIN;

    bool dataAvailable = false;
    for (int i = 10; i >= 0 && !dataAvailable; i--) {
        switch (poll(fds, 1, 1000)) {
            case -1:
                perror("poll failed");
                exit(1);
            case 0:
                printf("%d seconds left\n", i);
                break;
            default:
                dataAvailable = true;
        }
    }

    if (dataAvailable) {
        //read from stdin
    } else {
        fprintf(stderr, "no input\n");
        exit(1);
    }

    return 0;
}

关于c - C语言如何在不停止程序的情况下使用scanf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58142912/

相关文章:

c - 在事件查看器的情况下无法捕获 future 事件

c - 为什么linux内核中rwlock比seqlock更流行?

c - ARM恩智浦LPC2378 : Is is safe to modify GPIO pin output state via register access?

class - F# 类型类持久计数器

recursion - Prolog 中的递归搜索、累加器和计数器

php - 试图在 mysql 表中创建一个类似按钮的计数器,但是 UPDATE SET 不起作用

c - 检查输入是否为字符串的更好方法是什么?

jquery - 输入Jquery意外结束

html - td 宽度问题内的多个输入字段

css - 如何摆脱 mac 上 webkit 中 html5 搜索输入中的水平填充或缩进?