c - 如何让 C 程序等待几秒钟?
问题描述
这是我的代码的两行:
printf("Correct! \nTime took: %d seconds \n", (now - space));
if (((now + 5) == time(NULL)) && ((now-space) <= 10))
当然它不起作用,因为现在不是未来的 5 秒,但我的问题是让它等待 5 秒而不是“哦,现在不是 5 秒后,所以不,我不会打扰了。有没有办法使这项工作?
PS有人让我写操作系统,所以它是Windows。
解决方案
使用预处理器指令的或多或少的可移植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)
就是你要找的。
推荐阅读
- angular - 当我按顺序调用函数时,变量值设置不正确
- html - 如何将 svg 徽标转换为动画?
- google-maps - SBL-EAI-04116:“数据发送”期间的 HTTP Internet 异常:“安全通道支持中发生错误”,代码:“12157”
- c#-4.0 - 这背后的逻辑是什么
- html - 如何使用 flexbox 使卡片响应?
- swift - 当用户在 swift 中搜索搜索栏中的联系人时如何使用复选框进行联系人
- javascript - Angular - 如何用另一个对象替换对象属性?
- c# - 由于其他触发器,WPF 触发器无法正常工作
- virtual-machine - 将 VMDK 文件转换为压缩的 RAW 文件
- node.js - 修改测试API request-response时express发送的请求对象