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

Ankita Rane picture Ankita Rane · Mar 9, 2015 · Viewed 24.5k times · Source

I want to implement a time out feature in C++.

If the user does not input the value within 2 seconds then the program must display the time-out statement and ask the input again

EX(OUTPUT SCREEN):

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`

Code:

#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;  
} 

I have worked on the above code. But this happens only while entering the WHILE loop. How shall i do it in a way so that, I get the required output.

Answer

Akki picture Akki · Mar 9, 2015
#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;
}

Output:

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