【问题标题】:Print, delay and erase current line in C在 C 中打印、延迟和擦除当前行
【发布时间】:2016-07-14 03:01:45
【问题描述】:

我想实时打印程序开始后经过的秒数。首先输出为“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("\33[A");    //vt100 char, moves cursor up
            printf("\33[2K");   //vt100 char, erases current line
            printf("%ld\n", time/CLOCKS_PER_SEC);

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

我在 Ubuntu 上使用 gcc 编译器。

【问题讨论】:

    标签: c newline backspace time.h


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2010-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多