如何在一段时间后停用输入语句?

Xpl*_*ive 5 c c++ input cin

我们知道输入函数或运算符(cin,scanf,get ... .etc)等输入表格用户这次没有限制.

现在,我会问一个问题和用户给出答案,直到现在没有问题,但我的问题是"用户有时间(可能30或40秒)给出输入,如果他失败,那么输入语句将自动停用和执行下一个声明."

我想你得到了我的问题.那么请在这种情况下帮助我.如果有人给我一些真正有用的示例代码会更好.

我在Windows 7中使用codebolck 12.11.

alk*_*alk 10

*IX'系统的方法(包括Windows上的Cygwin):

您可以使用alarm()安排SIGALRM,然后使用read(fileno(stdin), ...).

当信号到达时,read()应返回-1并设置errnoEINTR.

例:

#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;
}
Run Code Online (Sandbox Code Playgroud)

注意:在上面的示例中,阻塞调用read()将在任何到达的信号上中断.避免这种情况的代码留给了读者...... :-)