Looking for code to stop at a program at a certain time.

Impatient neophyte to C++. Just learning and naturally impatient so working on program. Not a lot of writeup on dealing with "time" in an easily understandable lingo to neophytes. As a matter of fact in the two books to teach about C++ neither of them deals in anyway with "time" except for using time(NULL) for seeding the random number generator. Hoping someone would help -or- actually write code to stop a program at 1800 hours.

From what I've been able to decipher is that there is a class of variables like int or char or double to work with "time." But then I get lost. Haven't developed good proficiency in calling functions so my understanding of dealing with "time" is undoubtedly hindered by that.

Basically I would like a Bool variable named "termination_time" to switch to true when the time becomes 1800 hours.

Thank you.

Have a Great Day,
Jim
Do you want the program to stop after it has been executing for 1800 hours, or to stop execution at 6:00p.m.?

Edit: I'm guessing the latter.
Try this and look around the other links at this page:
http://www.cplusplus.com/reference/clibrary/ctime/localtime/
Last edited on
Yes, I am looking for the program to stop execution at 6:00 pm.

I have spent like three or four hours studying the link at: http://www.cplusplus.com/reference/clibrary/ctime/localtime/ and associated pages. At this point in my learning it just seems like some issue that to be quite frank I can't get a grasp of.
locatltime is what you want:

1
2
3
4
tm* thetime = localtime( time(0) );

if(tm->tmhour >= 18)
  exit(0);



Note the above code isn't perfect. Specifically it will close the program at any time between 6 PM and midnight. So if you try to run the program at 9 PM it will immediately close.

If you want to close only when the time becomes 6 PM, you'll need to get more clever. Like maybe check the date on startup:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
  // once on program startup
  tm* thetime = localtime( time(0) );

  noclosedate = -1;  // don't close the program on noclosedate
  if(thetime->hour >= 18)   // if already after 6 PM...
    noclosedate = thetime->yday;  // then don't close it today
}

{
  // later in the program
  tm* thetime = localtime( time(0) );

  if( noclosedate != thetime->yday )  // if it's not the noclose date, we can close
  {
    if(thetime->hour >= 18)
      exit(0);
  }
}



Note I didn't actually test any of this
Thank you!

I hadn't even gotten around to considering that I needed something to cause the program to run after 6:00 pm. I appreciate your foresight. It also gives me something so I can start to understand the basics of dealing with "time" in C++

Have a Great Day,
Jim
Topic archived. No new replies allowed.