如何在C中的某个时间后停止while循环

use*_*568 2 c

如何在C中的某个时间后停止while循环,我在c ++中完成它并且我尝试将其转换为c(下面)但它没有工作

#include <time.h>

int main(void)
{
    time_t endwait;
    time_t start;

    endwait = start + seconds ;
    while (start < endwait)
    {
        /* Do stuff while waiting */
    }
}
Run Code Online (Sandbox Code Playgroud)

abl*_*igh 7

在C中,没有构造函数,因此time_t start;只需声明一个类型的变量time_t.它没有设置为等于当前时间.因此,您需要在循环之前读取当前时间(并将其分配给starttime),并在循环内(或在while条件内)读取它.

此外,循环应该是

while ((currenttime = [code to assign time]) < endwait)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

或更整洁

while ([code to assign time] < endwait)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

IE看当前时间,而不是启动时间.

为了读取时间,你想要使用time(NULL)(如果你在几秒钟内使用时间值.所以你完成的程序看起来像(未经测试):

#include <time.h>

int main(void)
{
    time_t endwait;
    int seconds = 123;

    endwait = time (NULL) + seconds ;
    while (time (NULL) < endwait)
    {
        /* Do stuff while waiting */
    }
}
Run Code Online (Sandbox Code Playgroud)

另请注意,如果秒数很小,您可能希望使用更高的精度gettimeofday.这样可以防止等待1秒钟等待0秒到1秒之间的任何事情.


小智 5

如何尝试我的测试代码:

#include <stdio.h>
#include <time.h>
#include <unistd.h>

int main(void)
{
    time_t endwait;
    time_t start = time(NULL);
    time_t seconds = 10; // end loop after this time has elapsed

    endwait = start + seconds;

    printf("start time is : %s", ctime(&start));

    while (start < endwait)
    {
        /* Do stuff while waiting */
        sleep(1);   // sleep 1s.
        start = time(NULL);
        printf("loop time is : %s", ctime(&start));
    }

    printf("end time is %s", ctime(&endwait));

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

示例输出是:

wugq@SSDEV016:~/tools/test $ ./a.out
start time is : Fri Jan 17 17:12:57 2014
loop time is : Fri Jan 17 17:12:58 2014
loop time is : Fri Jan 17 17:12:59 2014
loop time is : Fri Jan 17 17:13:00 2014
loop time is : Fri Jan 17 17:13:01 2014
loop time is : Fri Jan 17 17:13:02 2014
loop time is : Fri Jan 17 17:13:03 2014
loop time is : Fri Jan 17 17:13:04 2014
loop time is : Fri Jan 17 17:13:05 2014
loop time is : Fri Jan 17 17:13:06 2014
loop time is : Fri Jan 17 17:13:07 2014
end time is Fri Jan 17 17:13:07 2014
Run Code Online (Sandbox Code Playgroud)