如何在特定时间后从`std :: cin`超时读取

San*_*ahu 4 c++ linux

我写了一个小程序,

int main(int argc, char *argv[])
{
    int n;
    std::cout << "Before reading from cin" << std::endl;

    // Below reading from cin should be executed within stipulated time
    bool b=std::cin >> n;
    if (b)
          std::cout << "input is integer for n and it's correct" << std::endl;
    else
          std::cout << "Either n is not integer or no input for n" << std::endl;
    return 0;
 }
Run Code Online (Sandbox Code Playgroud)

读取std::cin是阻塞因此程序等待直到程序或用户提供一些输入的外部中断(如信号).

我应该如何让语句std::cin >> n等待一段时间(可能使用sleep()系统调用)进行用户输入?如果用户没有提供输入并且在规定时间完成后(比如10秒),程序应该恢复到下一条指令(即if (b==1)声明之后).

Jer*_*ner 8

这对我有用(请注意,这在Windows下不起作用):

#include <iostream>
#include <sys/select.h>

using namespace std;

int main(int argc, char *argv[])
{
    int n;
    cout<<"Before performing cin operation"<<endl;

    //Below cin operation should be executed within stipulated period of time
    fd_set readSet;
    FD_ZERO(&readSet);
    FD_SET(STDIN_FILENO, &readSet);
    struct timeval tv = {10, 0};  // 10 seconds, 0 microseconds;
    if (select(STDIN_FILENO+1, &readSet, NULL, NULL, &tv) < 0) perror("select");

    bool b = (FD_ISSET(STDIN_FILENO, &readSet)) ? (cin>>n) : false;

    if(b==1)
          cout<<"input is integer for n and it's correct"<<endl;
    else
          cout<<"Either n is not integer or no input for n"<<endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • Windows等价物将是`WaitForSingleObject`.请注意,在Windows上,标准输入的HANDLE不是固定的,您必须使用`GetStdHandle`检索它. (3认同)

Mat*_*son 4

使用标准 C 或 C++ 函数无法做到这一点。

使用非标准代码的方法有很多种,但您很可能必须将输入作为字符串或单独的按键来处理,而不是能够读取像cin >> x >> y;wherexyare 任何 C++ 类型的任意变量这样的输入。

实现这一目标的最简单方法是使用 ncurses 库 - 特别是当您在 Linux 上时。

timeout函数将允许您设置超时(以毫秒为单位),并且您可以使用它getstr()来读取字符串或scanw()读取 C scanf 样式输入。