Refresh output on terminal / console

Hi!
I would like to make some output in the terminal which should appear while the program continues to run. The problem is that the output appears only when the program finishes, although the place in the code is much earlier.

As an example i give the following little program, which counts from 0 to 9999:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    bool printed = 0;
    cout << "i =  ";
    for(int i=0;i<10000;i++){
        for(int j=0;j<100;j++)
            for(int k=0;k<1000;k++){
                if(!printed){
                    if(i<11)
                        cout << "\b" << i;
                    else if(i<101)
                        cout << "\b\b" << i;
                    else if(i<1001)
                        cout << "\b\b\b" << i;
                    else
                        cout << "\b\b\b\b" << i;
                    printed = 1;
                }
            }
        printed = 0;
    }
    cout << endl;


The "\b" deletes a character from the terminal. Its to print the output "on top" of the old one...

While the above program runs fine and does what its supposed to do, the following, slightly changed version, gives the output only when the program finished running. Thus you don't even see the values that should have appeared in the meantime...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    bool printed = 0;
    cout << "i =  ";
    for(int i=0;i<100;i++){
        for(int j=0;j<10000;j++)
            for(int k=0;k<1000;k++){
                if(!printed){
                    if(i<11)
                        cout << "\b" << i;
                    else if(i<101)
                        cout << "\b\b" << i;
                    else if(i<1001)
                        cout << "\b\b\b" << i;
                    else
                        cout << "\b\b\b\b" << i;
                    printed = 1;
                }
            }
        printed = 0;
    }
    cout << endl;


What I changed is just the number of "junk" loops, to simulate some "heavy calculations". Now the output is not all the numbers from 0 to 99, as it should be, but first nothing and when the loops are finished, the final number, 99, appears.

This problem also occurs in a useful program, where the different loops are actually filled with some calculations and I would like to get some state information in between to know how far the calculations have progressed (as they take a while...).
std::cout is line buffered, meaning that the output isn't actually flushed to the screen until one of three conditions
occur:

1) A newline is encountered in the stream (you don't have any).
2) An explicit "std::cout << std::flush;" is done (you don't do it).
3) The internal buffer is full (it's big enough in your case to hold all of the output).

Thank you! The "flush" version is the desired one in my case...
Topic archived. No new replies allowed.