Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用C语言打印、延迟和擦除当前行_C_Newline_Backspace_Time.h - Fatal编程技术网

用C语言打印、延迟和擦除当前行

用C语言打印、延迟和擦除当前行,c,newline,backspace,time.h,C,Newline,Backspace,Time.h,我想实时打印程序启动后经过的秒数。首先,输出为“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

我想实时打印程序启动后经过的秒数。首先,输出为“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);
        }
    }
}

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


我正在Ubuntu上使用gcc编译器。

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

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

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

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