简体   繁体   English

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

[英]Print, delay and erase current line in C

I want to print the seconds elapsed in real time since the program began.我想实时打印自程序开始以来经过的秒数。 First the output is "0".首先输出为“0”。 After one second, the "0" is replaced by "1", and so on.一秒钟后,“0”被“1”替换,依此类推。 Here is the code I wrote initially.这是我最初编写的代码。

#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);
        }
    }
}

This gave an output "7" at the end of 7 seconds only.这仅在 7 秒结束时给出输出“7”。

If I make the following replacements, the code works fine.如果我进行以下替换,代码工作正常。

    printf("%ld", 0);

by经过

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

and

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

by经过

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

The problem seems that the output wont be sent until the current line is completely determined.问题似乎是在完全确定当前行之前不会发送输出。 What is happening here?这里发生了什么?

I am using gcc compiler on Ubuntu.我在 Ubuntu 上使用 gcc 编译器。

The output stream that you are writing to with printf() will buffer until the newline is received.您使用 printf() 写入的输出流将缓冲,直到收到换行符。 Since you aren't sending a newline then you get no flush until your application exits or the buffer fills up.由于您没有发送换行符,因此在应用程序退出或缓冲区填满之前不会刷新。

You can flush the output buffer yourself after each printf(), as hyde said in the comment above using fflush(stdout).您可以在每个 printf() 之后自己刷新输出缓冲区,正如 hyde 在上面使用 fflush(stdout) 的评论中所说的那样。

Or you can disable buffering by using setbuf( stdout, NULL );或者您可以使用 setbuf( stdout, NULL ); 禁用缓冲。

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

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