如何在C++中使用定时器强制在给定时间内输入?

How to use a timer in C++ to force input within a given time?

我想在 C++ 中实现超时功能。

如果用户在 2 秒内没有输入值,则程序必须显示超时语句并再次询问输入

EX(输出屏幕):

Timer=0;  
Please enter the input:       //if input is not given within 2 seconds then  
Time-out: 2 seconds  
Timer again set to 0  
Please enter the input:  //if input is not given within 2 seconds then  
Time-out: 2 seconds  
Timer again set to 0  
Please enter the input:22  
Data accepted  
Terminate the program`

代码:

#include<iostream>  
 #include<time.h>  
 using namespace std;  
 int main()  
{  
    clock_t endwait;  
    endwait =  2000 ;  
   cout<<endwait;  
   while (clock() < endwait)  
  {  
         cout<<"Please enter the input:";  
  }  
   return 0;  
} 

我已经完成了上面的代码。但这只会在进入 WHILE 循环时发生。我该如何做才能得到所需的输出。

恐怕无法以标准方式实现,因为 I/O 默认情况下,操作会阻塞调用进程,直到它完成或遇到错误。
您可以通过创建一个线程来解决这个问题,该线程检查输入是否已完成并在需要时进入休眠状态。但这并不实用。

问题在于抽象 iostream/FILEs 给你:你无权访问基础源,即 OS "understands"也因此能够为您提供那种功能(即 I/O 轮询)。

一个单独的线程是不够的,因为console读取函数超时后还是运行

在 POSIX 上,您可以设置一个定时器,它会产生一个信号并导致读取失败 -EINTR

在 Windows 上,您可以使用 ReadConsoleInputWaitForSingleObject 实现低级控制台 I/O 超时...但是您需要执行自己的行缓冲.

另一个想法是在 OVERLAPPED 模式下使用 ReadFile 并等待超时完成事件,但这不适用于控制台,请参阅 Using overlapped IO for console input?

最后,新的 Windows 版本(Vista 及更高版本)允许您使用 CancelIoEx 克服 "blocking read is not cancelled by timeout" 问题。如果你从一个单独的线程调用它,它会提前触发 ReadFile 到 return;您不必自己实现行缓冲。

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <condition_variable>
using namespace std;
condition_variable cv;

int value;

void read_value() {
    cin >> value;
    cv.notify_one();
}

int main()
{
    cout << "Please enter the input: ";
    thread th(read_value);

    mutex mtx;
    unique_lock<mutex> lck(mtx);
    while (cv.wait_for(lck, chrono::seconds(2)) == cv_status::timeout)
    {
        cout << "\nTime-Out: 2 second:";
        cout << "\nPlease enter the input:";
    }
    cout << "You entered: " << value << '\n';

    th.join();

    return 0;
}

输出:

Please enter the input:  
Time-Out: 2 second:  
Please enter the input:  
Time-Out: 2 second:  
Please enter the input:22  
You entered: 22  

我认为没有必要为此使用复杂的代码(多线程或互斥)。请参阅下面的代码:

#include <iostream>
#include <time.h>
#include <conio.h>

using namespace std;

int main()
{
    int numInput;

    clock_t start = clock();

    cout << "Timer: 2 sec"<<endl;

    cout << "Please enter the input: ";

    while ( ! _kbhit() ) //Check for keyboard hit
    {
        //Check if 2 sec timer expired or not
        if (((clock () - start)/ CLOCKS_PER_SEC ) >= 2) 
        {
            cout << "\nTimeout  2 sec . . ." << endl;
            cout << "Please enter the input: ";
            start = clock();                            //Set new timer
        }
    }

    //Get the input here
    cin >> numInput;

    cout << "Data accepted: " << numInput << endl;

    _getch();

    return 0;
}

我已经使用 kbhit() 函数解决了你的问题。代码如下:-

    #include <conio.h>
    #include <iostream>
    #include <windows.h>

    using namespace std;

    int main()
    {
        int i;
        DWORD start_time, check_time;
        start_time=GetTickCount();
        check_time=start_time+2000;
        while(!kbhit())
        {
            cout<<"Please enter the input:"<<endl;
            while((check_time>GetTickCount()))
            {
                if (kbhit())
                {
                    i=getch();
                    cout<<"Data accepted"<<endl;
                    return 0;
                }
            }
            cout<<"Time-out: 2 seconds"<<endl;
            cout<<"Timer again set to 0"<<endl;
            start_time=GetTickCount();
            check_time=start_time+2000;
        }
    return 0;

    }