hey guyz... i'm new here... i just want to know how i could end my program after a certain amount of time has passed by...

I'm doing a "text twist" program where after 2.30minutes and if the user still has not guessed the correct answer, the program will end... i'm stuck on the timer part because i can't end the program after a certain amount of time....

here's the code i have for the input:

do
{
    cout << "Please input your guess here: " ;
    cin>> l;
 }while(b.check_answer(l));

could i use Sleep() for this part? i just need an point to the right direction 'cause i'm stuck right now.. thanks!:D

What you can do is:

1. set a global to 0

2. start a second thread that sleeps 1 second 150 times in a loop,
on every loop it increments the loop counter, checks for a kill variable,
and if the loop counter is 150 sets the global to 1, and dies. if the kill variable is
1 it exits immediately, this allows a clean shutdown.

3. Your main thread checks for the global, and if it is 1, it exits.

The other way of doing it is to set a variable to time() + 150,
and on every loop get a new value for time() until it is GTE the
original cutoff time. If your gaime spends most of its time waiting
this should not be a problem, and you don't have to learn how
to deal with threads.

@plum
Aslong as he doesn't mind his program being 100% accurate the latter is good idea.

A bit more information about the latter for you,

time() comes with the including ctime,
i'd suggest having a read about the ctime header and all of its functions

http://www.cplusplus.com/reference/clibrary/ctime/

Chris

I'd suggest that you use the clock() function. Examply of use:

#include <ctime>
#include <iostream>

#define SECONDS number of seconds here..

using namespace std;

int main(void)
{
int guess;
cin>>guess;

if(clock()>SECONDS*CLOCKS_PER_SEC) return 0;

return 0;
}

Note: clock() returns the number of milliseconds passed since the program began, and CLOCKS_PER_SEC is a defined constant, and its value is 1000;

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.