tags:

views:

47

answers:

1

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.

+1  A: 

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?

Tyler McHenry
Thanks sir. Now I think I get it, let me try.
arscariosus
Thanks again sir. All working fine now. :D
arscariosus