user2845121
user2845121

Reputation: 113

Wait only 5 second for user input

I want to write a simple c program in turbo c++ 4.5 editor such that in only wait 5 seconds for user input. As an example,

#include <stdio.h>

void main()
{
  int value = 0;
  printf("Enter a non-zero number: ");

  // wait only 5 seconds for user input
  scanf("%d",&value);
  if(value != 0) {
    printf("User input a number");
  } else {
    printf("User dont give input");
  }
}

So, what will be the code for 5 seconds wait for 'scanf' functionality and otherwise execute if-else part.

Upvotes: 5

Views: 6354

Answers (3)

mirabilos
mirabilos

Reputation: 5327

Try a select(2) loop: https://www.mirbsd.org/man2/select on stdin (fd#0) with a timeout of 5 seconds; run the scanf(3) only if select returns indicating there is data. (See the c_read() function in the mksh source code for an example.)

Other functions, like poll(2), are also possible. Nonblocking I/O is a bit overkill.

OK, here’s a working (on MirBSD) example using select:

#include <sys/types.h>
#include <sys/time.h>
#include <err.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int
main(void)
{
    int value = 0;
    struct timeval tmo;
    fd_set readfds;

    printf("Enter a non-zero number: ");
    fflush(stdout);

    /* wait only 5 seconds for user input */
    FD_ZERO(&readfds);
    FD_SET(0, &readfds);
    tmo.tv_sec = 5;
    tmo.tv_usec = 0;

    switch (select(1, &readfds, NULL, NULL, &tmo)) {
    case -1:
        err(1, "select");
        break;
    case 0:
        printf("User dont give input");
        return (1);
    }

    scanf("%d", &value);
    if (value != 0) {
        printf("User input a number");
    } else {
        printf("User dont give input");
    }
    return (0);
}

You might want to play with the exit codes a bit and sprinkle a few \n throughout the code. The fflush(stdout); is important so that the prompt is shown in the first place…

Upvotes: 9

Farouq Jouti
Farouq Jouti

Reputation: 1667

well you can use the halfdelay() function from the curses library

Upvotes: 0

Sohil Omer
Sohil Omer

Reputation: 1181

#include <stdio.h>
#include <signal.h>

void handler(int signo)
{
  return;
}

int main()
{
  int x;
  struct sigaction sa;

  sa.sa_handler = handler;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = 0;
  sigaction(SIGALRM, &sa, NULL);

  alarm(5);

  if (scanf("%d", &x) == 1)
  {
    printf("%d\n", x);
    alarm(0); // cancel the alarm
  }
  else
  {
    printf("timedout\n");
  }
  return 0;
}

Upvotes: 2

Related Questions