在 C 中打印、延迟和擦除当前行

Print, delay and erase current line in C

我想实时打印程序开始后经过的秒数。首先输出为“0”。一秒钟后,“0”被“1”取代,依此类推。这是我最初写的代码。

#include<stdio.h>
#include<time.h>

void main ()
{
  long int time;

  printf("Hello, let us measure the time!\n");

  time=clock();
    printf("%ld", 0);

  while(time/CLOCKS_PER_SEC<7)
    {
        time=clock();
        if(time%CLOCKS_PER_SEC==0)
        {
            printf("\r");
            printf("%ld", time/CLOCKS_PER_SEC);
        }
    }
}

这仅在 7 秒结束时给出了输出“7”。

如果我进行以下替换,代码可以正常工作。

    printf("%ld", 0);

来自

    printf("%ld\n", 0);

            printf("\r");
            printf("%ld", time/CLOCKS_PER_SEC);

来自

            printf("[A");    //vt100 char, moves cursor up
            printf("[2K");   //vt100 char, erases current line
            printf("%ld\n", time/CLOCKS_PER_SEC);

问题似乎是在完全确定当前行之前不会发送输出。这里发生了什么?

我在 Ubuntu 上使用 gcc 编译器。

您使用 printf() 写入的输出流将缓冲,直到收到换行符。由于您不发送换行符,因此在您的应用程序退出或缓冲区填满之前,您不会刷新。

您可以在每次 printf() 之后自行刷新输出缓冲区,正如 hyde 在上面的评论中使用 fflush(stdout) 所说的那样。

或者您可以使用 setbuf( stdout, NULL );

禁用缓冲