Kleiver Marcano
Kleiver Marcano

Reputation: 37

How to use scanf without stopping the program C language?

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?

Upvotes: 0

Views: 733

Answers (1)

Stephan Schlecht
Stephan Schlecht

Reputation: 27106

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

Upvotes: 2

Related Questions