Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deactivate input statement after some time?

Tags:

c++

c

input

cin

We know input function or operator (cin, scanf,gets….etc) wait to take input form user & this time has no limit.

Now, I will ask a question & user give the answer, till now there no problem but my problem is “user has a time(may 30 or 40 sec) to give the input, if he fail then input statement will automatically deactivated & execute next statement.”

I think you get my problem. Then please help me in this situation. It will be better if someone give me some really working example code.

I use codebolck 12.11 in windows 7.

like image 489
Xplosive Avatar asked Aug 17 '13 14:08

Xplosive


1 Answers

An approach for *IX'ish systems (including Cygwin on windows):

You could use alarm() to schedule a SIGALRM, then use read(fileno(stdin), ...).

When the signal arrives read() shall return with -1 and had set errno to EINTR.

Example:

#define _POSIX_SOURCE 1

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>

void handler_SIGALRM(int signo)
{
  signo = 0; /* Get rid of warning "unused parameter ‘signo’" (in a portable way). */

  /* Do nothing. */
}

int main()
{
  /* Override SIGALRM's default handler, as the default handler might end the program. */
  {
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));

    sa.sa_handler = handler_SIGALRM;

    if (-1 == sigaction(SIGALRM, &sa, NULL ))
    {
      perror("sigaction() failed");
      exit(EXIT_FAILURE);
    }
  }

  alarm(2); /* Set alarm to occur in two seconds. */

  {
    char buffer[16] = { 0 };

    int result = read(fileno(stdin), buffer, sizeof(buffer) - 1);
    if (-1 == result)
    {
      if (EINTR != errno)
      {
        perror("read() failed");
        exit(EXIT_FAILURE);
      }

      printf("Game over!\n");
    }
    else
    {
      alarm(0); /* Switch of alarm. */

      printf("You entered '%s'\n", buffer);
    }
  }

  return EXIT_SUCCESS;
}

Note: In the example above the blocking call to read() would be interupted on any signal arriving. The code to avoid this is left as an execise to the reader ... :-)

like image 130
alk Avatar answered Sep 28 '22 04:09

alk