简体   繁体   English

我正在尝试使用 C 中的 \r 更新命令行 output 3 次,但为什么它会跳过我的第二个 printf 语句?

[英]I am trying to update the command line output 3 times using \r in C, but why does it skip over my second printf statement?

Here is my code:这是我的代码:

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

int main() {
    printf("hello");
    sleep(1);
    fflush(stdout);
    printf("\rworld");
    sleep(1);
    fflush(stdout);
    printf("\r!    \n");
    sleep(1);
    return 0;
}

It displays "Hello" for a second, does nothing for another second, and then goes straight to "."它会显示“Hello”一秒钟,再过一秒钟什么也不做,然后直接转到“.”。 I have tried to change the sleep durations and a few other things but nothing has fixed it?我试图改变睡眠持续时间和其他一些事情,但没有解决它? What am I doing wrong?我究竟做错了什么?

Flush before sleep to insure timely display.睡前冲洗,确保及时显示。

stdout buffering mechanisms are implementation defined. stdout缓冲机制是实现定义的。 Yet fflush() will get the output done promptly.然而fflush()会迅速完成 output 。

int main(void) {
    printf("hello");
    fflush(stdout);
    sleep(1);

    printf("\rworld");
    fflush(stdout);
    sleep(1);

    printf("\r!    \n");
    fflush(stdout);
    sleep(1);

    return 0;
}

doing this should work这样做应该有效

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

int main() {
    printf("hello");
    sleep(1);
    fflush(stdout);
    printf("\rworld");
    sleep(1);
    fflush(stdout);
    printf("\r!    \n");
    sleep(1);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM