温馨提示×

c语言sleep函数如何使用

小亿
154
2024-04-28 09:59:42
栏目: 编程语言

在C语言中,可以使用sleep()函数来使程序暂停执行一段时间。sleep()函数在<unistd.h>头文件中定义,其原型为:

unsigned int sleep(unsigned int seconds);

其中seconds参数表示程序暂停的秒数。调用sleep()函数后,程序将会暂停执行指定的秒数,然后继续执行后面的代码。

下面是一个示例代码,演示了如何使用sleep()函数来使程序暂停执行5秒钟:

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

int main() {
    printf("Hello, ");
    fflush(stdout); // 刷新输出缓冲区,确保"Hello, "被立即输出

    sleep(5); // 暂停5秒

    printf("world!\n");

    return 0;
}

在上面的示例中,程序先打印"Hello, “,然后调用sleep(5)函数使程序暂停5秒,最后再打印"world!\n”。运行该程序时,可以看到在暂停5秒后,才会打印出"world!\n"。

0