You are here:

C++/how to set amount of time for user input

Advertisement


Question
Here is my code I attempted, am trying to set a timer on user input. What I mean is how can I set the timer to 60 seconds so user have 60 seconds to enter in their name, and if they take too long, the program will automatically terminate the getline and print out NO NAME ENTERED! message. Thanks!!

#include <iostream>
#include <ctime>
#include<string>
using namespace std;

int main(){
 string name;
 cout << "Enter your name: ";
 int endTime= clock()+5000;
 
 while(clock() < endTime)
 {
   getline(cin, name);
   if( clock() > endTime && (name.empty()))

     break;
 }
 
 cout << "NO NAME ENTERED!!" << endl;
 
 return 0;
}

Answer
Hello Mike.

Once you call a function like getline, you have no control over the program until getline returns. Once it returns, you can check the time, but I guess that is not what you want. The solution is to use _kbhit. This is a common function, if it is not a standard one. On my Windows system, the functions starts with an underscore. On other systems, it may not have the underscore.

Here is some sample C++ code. I believe you can understand it. If not, just ask about it.

#include <time.h>
#include <string>
#include <iostream>
#include <conio.h>
#include <Windows.h> // for Windows Sleep
using namespace std;

void kbhitExample()
{
   while(true)
   {
       // expire in 60 seconds.
       time_t expiry = time(NULL) + 60;

       string input;
       while(true)
       {
           if (time(NULL) > expiry)
           {
               cout << "Expired\n";
               break;
           }

           if (_kbhit())
           {
               char ch = (char)_getch();
               _putch(ch); // echo character back to the screen
               if (ch == '\n' || ch == '\r') break;
               else input.insert(input.end(), 1, ch);
           }
           else
           {
               Sleep(1); // or sleep(1) if using unix/linux
           }
       }

       cout << "String is <" << input << ">\n";
   }
}

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.