简体   繁体   中英

How do I create a timer using the time.h library?

This is not a homework, it's more of a challenge from our prof but I'll be tagging it as one nonetheless.

The problem is to create a typing game that has 3 levels with matching difficulty, different time limits (in seconds) and scores. Now I don't have any problems with the program itself, what I'm having problem is implementing the timer, that should be OS independent (I assume, since the only hint says it's time.h ). What I did is wrong, for it's only a rough guess from what I read about the time.h, it's also ugly code:

time_t start;
int timer = time(&start);
...
time_t current;
for(ctr=0;ctr<10;ctr++)
{
    ...
    if(time(&current) == (timer+40))
      {    
           break;
      }
    ...
}

Works sometimes but doesn't most of the time since it's only a rough guess. Any suggestions would be appreciated.

First off, you don't need to provide a time_t* argument to the time function. If you're just going to use its return value, it's fine (and very common) to call time(NULL) . That way you can eliminate the start and current variables if they aren't otherwise being used.

Second, the return value from time is time_t , not int , so timer should be of type time_t .

Finally, look at your test

if(time(&current) == (timer+40))

and consider what happens if the time passed 40 seconds since the start while you were doing something else above the test, and is now, say, 43 second since the start. Don't you still want to break? So is == the appropriate test?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM