views:

73

answers:

4

Hello, I have been trying to use fflush to make a progress bar. To test fflush, I wrote the small code below.

It works as it supposed to when I uncomment "sleep(1);" but it works in an unexpected way if it remains commented out. It prints the first dash, waits than prints all remaining 9 of them and quits.

I don't understand why it makes a difference. Any ideas? Thanks for reading.

int main()
{
    int f,j;
    j =0;
    for(f=0;f<10;f++)
     {
        printf("-");
        fflush(stdout);
        while(j++<1000000000);
        //sleep(1);
     }
}
+2  A: 

You need to set j back to zero after the while loop. The next iteration it will just skip over the while loop.

syork
A: 

This is because you don't reset the inner loop counter j to zero at each outer loop iteration, i.e. the while() is executed only the first time around. Nothing to so with fflush() :)

Nikolai N Fetissov
A: 

For the first 'for' iteration f=0, it will print the first dash, then will run j up to 1 billion, and then it will print the nine remaining dashes because j is greater than 1 billion hence no more wait or delay. That is how it should run if sleep(1) is commented out.

You may wish to add line j=0; after the while loop to reset j to zero.

When you uncomment sleep(1) there will be a small almost unnoticeable delay (I guess 1 millisecond) after printing each dash.

Good luck,

Julio Mendoza-Medina.

Julio
A: 

Change your for loop like so:

from:

for(f=0;f<10;f++)

to:

for(f=0, j=0; f<10; f++, j=0)

Ziffusion