首页 > 解决方案 > 如何让 C 程序等待几秒钟?

问题描述

这是我的代码的两行:

    printf("Correct! \nTime took: %d seconds \n", (now - space));
    if (((now + 5) == time(NULL)) && ((now-space) <= 10))

当然它不起作用,因为现在不是未来的 5 秒,但我的问题是让它等待 5 秒而不是“哦,现在不是 5 秒后,所以不,我不会打扰了。有没有办法使这项工作?

PS有人让我写操作系统,所以它是Windows。

标签: c

解决方案


使用预处理器指令的或多或少的可移植sleep函数(以微秒为单位的时间):

#ifdef _WIN32
//  For Windows (32- and 64-bit)
#   include <windows.h>
#   define SLEEP(msecs) Sleep(msecs)
#elif __unix
//  For linux, OSX, and other unixes
#   define _POSIX_C_SOURCE 199309L // or greater
#   include <time.h>
#   define SLEEP(msecs) do {            \
        struct timespec ts;             \
        ts.tv_sec = msecs/1000;         \
        ts.tv_nsec = msecs%1000*1000;   \
        nanosleep(&ts, NULL);           \
        } while (0)
#else
#   error "Unknown system"
#endif

#include <stdio.h>

int main(void)
{
    printf("Hello\n");
    SLEEP(1000); // 1 second
    printf("World\n");
    return 0;
}

我用的是 Windows 10

然后Sleep(1000)就是你要找的。


推荐阅读