You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C语言中用\r更新命令行输出3次,为何跳过第二条printf语句?

问题原因与解决方法

你的问题出在**fflush的调用时机**上:stdout默认是行缓冲模式,不带换行符的printf输出会暂存在缓冲区,不会立刻显示到终端。你当前代码是先sleep再fflush,导致前一个printf的内容要等休眠结束后才会输出,紧接着就执行下一个printf,中间的world根本没机会在屏幕上停留显示。

实际执行逻辑是:

  1. 执行printf("hello"),内容存在缓冲区,屏幕无显示
  2. 休眠1秒,屏幕依然无内容
  3. 调用fflush,缓冲区的hello才显示到屏幕
  4. 立刻执行printf("\rworld"),内容进入缓冲区,屏幕仍显示hello
  5. 再休眠1秒,屏幕依然显示hello
  6. 调用fflush,\rworld输出覆盖hello,但紧接着就执行printf("\r! \n")
  7. 这个printf带换行符,会自动刷新缓冲区,! 立刻覆盖world并换行
  8. 最后休眠1秒,显示!

这就是你看到“先显示hello1秒,接着1秒无变化,然后直接显示!”的原因。

修正后的代码

把fflush移到printf之后、sleep之前,让每一次输出立刻显示并停留指定时间:

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

int main() {
    printf("hello");
    fflush(stdout); // 立即刷新缓冲区,显示hello
    sleep(1);
    
    printf("\rworld");
    fflush(stdout); // 立即刷新,用world覆盖hello
    sleep(1);
    
    printf("\r!    \n");
    fflush(stdout); // 带换行符时stdout会自动刷新,加上也不影响
    sleep(1);
    return 0;
}

修正后执行流程:

  • 显示hello并停留1秒
  • 光标回到行首,world覆盖hello并停留1秒
  • 光标回到行首,! 覆盖world并换行,停留1秒

内容的提问来源于stack exchange,提问作者Anivartin Anand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:01:01