我试图让我的代码在屏幕上打印一些内容,然后等待 1 秒,然后绕过 for 循环并再次打印 21 次。当我在 Windows 中的 CodeBlocks 中使用 #include 然后使用 Sleep(1000) 执行此操作时,它会起作用。但是,当我在 Ubuntu 虚拟机上使用 #include 和 sleep(1) 执行此操作时,所有内容都会从我的终端消失 21 秒,然后全部同时出现。我想我使用了错误的功能或其他东西。
有什么想法吗?
这是 Ubuntu 终端中的代码,最终会删除终端上已有的所有内容,等待 21 秒,然后仅打印“Hello”21 次。
#include <stdio.h>
#include <unistd.h>
int main()
{
for (int i = 0; i < 21; i++)
{
printf("Hello");
sleep(1);
}
}
这是 Windows 中的代码,每秒打印“Hello”,持续 21 秒,因此在 21 秒内在屏幕上打印 21 个 Hello。这就是我试图在我的 Ubuntu VM 中实现的目标。
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main() {
for (int i = 0; i < 21; i++)
{
printf("Hello");
Sleep(1000);
}
return 0;
}
最佳答案
在 UNIX 中,进程流缓冲 - 它们会累积 I/O,并且默认情况下不会在写入时立即“刷新”到底层设备。所以 - 你需要刷新流:
#include <stdio.h>
#include <unistd.h>
int main()
{
for (int i = 0; i < 21; i++)
{
printf("Hello");
fflush(stdout);
sleep(1);
}
}
我相信,如果您在“Hello”之后输出换行符“\n”,它也会起作用。
关于c - 如何在 for 循环中正确实现 sleep 函数? (乌类图),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55715722/