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

Ank*_*ane 7 c++ timer sliding-window

我想在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`
Run Code Online (Sandbox Code Playgroud)

码:

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

我已经处理了上面的代码.但这只在进入WHILE循环时发生.我该如何做到这一点,以便获得所需的输出.

Akk*_*kki 9

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

输出:

Please enter the input:  
Time-Out: 2 second:  
Please enter the input:  
Time-Out: 2 second:  
Please enter the input:22  
You entered: 22  
Run Code Online (Sandbox Code Playgroud)

  • 尽管这似乎可行,但实际上并未使cin超时。例如,如果用户要在提示后键入一个值,但在超时之前没有按回车键,但是在随后的提示中,用户确实按时按了回车键。用户输入的所有值(无论是否按回车键)都将附加到您的值上,因为该流永远不会被刷新。您可以考虑在某个时候停止并重新启动流或刷新输入流。很好地使用condition_variable! (3认同)