Home > OS >  Waiting for input for a while
Waiting for input for a while

Time:07-31

The program does not wait for the Enter key to be pressed, but it will wait indefinitely for the character to be entered and the "-" sign will never appear on the screen. How can I make the program wait for input only for a while?

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char c = 'A';

    system("stty raw"); 
    c = getchar();
    system("stty cooked");
    
    if (c == 'A')
        printf("-\n");
    else
        printf(" \n");

    return 0;
}

CodePudding user response:

There is no standard way to do what you want, but the use of stty makes me think that you're using a *nix system of some sort. You may then be able to use select (which is very old-school) to wait for input for a certain amount of time.

Here's an example of how you could wait for a second.

#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>

int main(void) {
    char c = 'A';

    int stdinfd = fileno(stdin); // your platform probably has a macro for this

    struct timeval timeout = {
        .tv_sec = 1, // seconds
        .tv_usec = 0 // microseconds
    };

    fd_set fds; // a set of file descriptors to wait for
    FD_ZERO(&fds); // initialize the set
    FD_SET(stdinfd, &fds); // put "stdin" in the set to wait for

    system("stty raw");
    int rv = select(stdinfd   1, &fds, NULL, NULL, &timeout);
    system("stty cooked");

    if(rv > 0) { // more than zero file descriptors are ready
        c = getchar();
        if(c == 'A')
            printf("-\n");
        else
            printf(" \n");
    } else {    // no file descriptors are ready (or there was an error)
        puts("timeout");
    }
}

Read your platform documentation for how to do stty raw and stty cooked without system calls.

CodePudding user response:

Since there is no standard way in C to do what you'd like, you could use a library, like one of the curses libraries, to do what you want. curses is available for most platforms in one form or the other. For Windows, you could install pdcurses. On *nix platforms, it's usually installed already.

Example:

#include <curses.h>
#include <stdio.h>

int main(void) {
    initscr();     // initialize curses
    timeout(1000); // set the input timeout in milliseconds

    int ch = getch();

    // restore the terminal I/O settings -
    // this is usually the last thing in a curses program:
    endwin(); 

    if(ch == ERR) {
        puts("timeout");
    } else {
        printf("you typed %c\n", ch);
    }
}
  • Related