我正在开始学习 C 编程,我正在尝试解决我正在学习的书中的练习课。我需要做的任务是将一行打印到终端,然后等待 2 秒,2 秒后将光标返回到终端中该行的开头,并用其他内容替换、覆盖该行。
书中的示例代码包含许多我还需要完成的其他任务的样板代码,目前我正在尝试自己隔离并解决第一个问题,但它不起作用,我不明白为什么。
这是我正在尝试的代码:
#include "stdio.h"
#include "time.h"
int main() {
const int DELAY = 2;
time_t wait_start = 0;
printf("We print this then wait 2 seconds");
//delay by repeating this empty for loop
wait_start = clock(); //the time when we start the delay and subtract this from the current time returned by clock()
for ( ; clock() - wait_start < DELAY * CLOCKS_PER_SEC; );
printf("\r");
printf("We did return the cursor to the beginning and print this after 2 seconds");
return 0;
}
我想要发生的是打印第一行,等待 2 秒,然后覆盖,用第二行替换第一行。
但是,当我执行此代码时,尽管有延迟,它似乎立即将光标返回到行的开头,并且它不会将第一行打印到终端,但 2 秒后它不会打印第二行。
有人可以帮我解释一下为什么会发生这种情况以及如何解决吗?
谢谢。
最佳答案
当您使用 printf 时,您会写入 stdout 缓冲区。它不必立即显示,除非您刷新它(使用 fflush()
)或编写换行符 (\n
),这会有效地刷新它。
关于c - 如何在C编程中使用带有延迟的\r回车符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70914796/