#include <iostream>
#include <windows.h>
#include <ctime>
using namespace std;
double time1;

int main()
{
 const double seconds1 = time(0);
 string string1;
 while(1)
 {
  long double seconds2 = time(0);
  if(seconds2 == seconds1 + 5)
  { cout << "Five seconds went by.\n\n"; break; }
 }
 cin.clear();
 cin.ignore(255, '\n');
 cin.get();
 return 0;
}

^ This outputs "Five seconds went by." after five seconds. Is there a way to throw in some sort of input so that the program can prompt the user for input and after five seconds say something like 'too late' and close? Or would I have to go about timing in a totally different way?

Recommended Answers

All 5 Replies

You cannot do that in C++.

Your question is not clear enough. I don't understand if you want to prompt the user and if after 5 seconds user didn't enter anything, program would say "too late" or you want the program to say "too late" after 5 seconds users entered the key.

If you want the 2nd, it's easy to do, but for the first one, you need threading.
One thread for time and one thread to wait for the user's input.

Sorry. I mean I want to prompt the user for input and if they don't enter anything after five seconds say something like 'too late.'

So, think about it. You want to do 2 things concurrently. That is not possible using only one stream. Therefore you need to use threads, one keeps track of time the other waiting for user input. Whichever happens first, continue with proper actions.

Google up "pthreads.h" library in C++.

Okay, I'll look into that. Thanks for the help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.