How to use scanf without stopping the program C language?

倖福魔咒の 提交于 2021-01-29 18:00:29

问题


I'm doing a counter where I'm showing how many seconds the user has to make the input. The problem is that when I use scanf(), the program will stop and will wait for the answer, but I don't want that. I'd like to keep running the counter even thought the user doesn't put anything.

Example:

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

What can i do to solve this?


回答1:


Like mentioned in the comments one possibility would be to use poll.

man poll says:

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.

In code it could look like this:

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


来源:https://stackoverflow.com/questions/58142912/how-to-use-scanf-without-stopping-the-program-c-language

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!