2

谁能告诉我如何在 c 中延迟或倒数?我的意思是在一秒钟后写下 1 和 2。我知道的唯一方法是

include<windows.h>

Sleep( 1000 /* milliseconds */ );

谁能告诉我另一种方法来做到这一点?(我有 Windows 8)

4

4 回答 4

2

如果您仅限于标准 C89

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

int main(void) {
    time_t t;

    /* wait until the Standard clock ticks */
    t = time(0);
    while (time(0) == t) /* void */;

    /* print 1 */
    puts("1");

    /* wait until the Standard clock ticks again */
    t = time(0);
    while (time(0) == t) /* void */;

    /* print 2 */
    puts("2");

    return 0;
}

如果您可以使用 POSIX:使用nanosleep()

于 2013-03-03T18:20:24.750 回答
2

您可以使用thrd_sleepC11 中提供的 ,并为其编写一个简单的包装器:

void sleep(time_t seconds){
    struct timespec ts, remaining;
    timespec_get(&ts, TIME_UTC);
    ts.tv_sec += seconds;
    while(thrd_sleep(&ts,&remaining) == -1){
        timespec_get(&ts, TIME_UTC);
        ts.tv_sec += remaining.tv_sec;
    }
}
于 2013-03-03T18:28:21.093 回答
1

设置alarm()一秒钟后触发的警报,然后调用pause()

于 2013-03-03T18:27:32.777 回答
0

的使用select()将是另一种也是可移植的解决方案,尽管非常非常规的方法来(只是)产生延迟。

于 2013-03-03T18:36:22.280 回答