I want to print the seconds elapsed in real time since the program began. First the output is "0". After one second, the "0" is replaced by "1", and so on. 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.
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.