c语言sleep函数怎样使用
在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!
");
return 0;
}
在上面的示例中,程序先打印"Hello, “,然后调用sleep(5)
函数使程序暂停5秒,最后再打印"world!
”。运行该程序时,可以看到在暂停5秒后,才会打印出"world!
"。
TOP