How do i stop a while loop after a certain time in C, i did it in c++ and i tried converting that to c (below) but it didnt work
#include <time.h>
int main(void)
{
time_t endwait;
time_t start;
endwait = start + seconds ;
while (start < endwait)
{
/* Do stuff while waiting */
}
}
In C, there are no constructors, so time_t start;
just declares a variable of type time_t
. It does not set that equal to the current time. You thus need to read the current time before the loop (and assign that to starttime), and read it within the loop (or within the while condition).
Also, the loop should be
while ((currenttime = [code to assign time]) < endwait)
{
...
}
or neater
while ([code to assign time] < endwait)
{
...
}
IE look at currenttime, not starttime.
In order to read the time, you want to use time(NULL)
(if you are using time values in seconds. So your completed program would look something like (untested):
#include <time.h>
int main(void)
{
time_t endwait;
int seconds = 123;
endwait = time (NULL) + seconds ;
while (time (NULL) < endwait)
{
/* Do stuff while waiting */
}
}
Note also that if the number of seconds is small, you might want to use the higher precision gettimeofday
. This will prevent waiting for 1 second waiting for anything from 0 seconds to 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With