BoeNoe BoeNoe - 10 days ago 5
C++ Question

Timing allow input in C++

I want to have a program where the user have 10 seconds to enter the password. If the timer goes over 10 seconds, the program displays a message. My current code is this:

#include <iostream>
#include <ctime>
#include <string>

int main(){
std::string password;

int start_s=clock();

int stop_s=clock();
if(stop_s-start_s <= 0){

std::cout << "TIME RAN OUT!";
}
std::cout << "Enter your password! \n";
std::cout << "Password: ";
std::cin >> password;
std::cout << "\n \n";

if (password == "password123"){

std::cout << "Correct!";
} else {
std::cout << "Wrong!";
}

}


This of course is not working... But I am not sure what to do next... Any ideas?

If you need more details, ask in the comments.

EDIT:

I just realized what the problem was... It took a time stamp and then quickly made another time stamp. And when the difference was found, it was below 0...

But I still don't know what to do next...

Answer

What you are trying to do is to have an non-blocking (asynchronous) read from stdin with a timeout of 10 seconds. This is not too tough but may involve many new concepts depending on your knowledge. What we need to do is:

  1. Place the standard input (STDIN) handle (handle = 0) into a 'watch-list'.
  2. Place a timeout on the watch-list.
  3. Whenever there is a change in the STDIN, process it.
  4. When the timeout has expired, check if what we have processed does the job.

In linux, the watch-list can be handled using FD_SET and a select system call. In Windows, you will need to use WaitForMultipleEvents.

I'm not sure I can do justice to explaining these concepts accurately for the purposes of this code. As a reference, another question which has some code pointers for exactly the same thing is here.

Comments