954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to end a program after a certain amount of time?

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

jetdreamer
Newbie Poster
1 post since Sep 2008
Reputation Points: 10
Solved Threads: 0
 

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.

plumsauce
Newbie Poster
6 posts since Sep 2008
Reputation Points: 10
Solved Threads: 0
 

@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

Freaky_Chris
Master Poster
702 posts since Apr 2008
Reputation Points: 325
Solved Threads: 118
 

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;

unbeatable0
Junior Poster in Training
90 posts since Sep 2008
Reputation Points: 42
Solved Threads: 13
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You