0

Here is a simple program designed to keep track of loop progress and print it at certain stages (every 10% in this example).

using namespace std;

int main() {
    double step = 0.1;
    double last_progress = 0;
    int num_iter = 100;
    for (int i = 1; i <= num_iter; ++i) {
        double k = i * 1.0 / num_iter;
        if (k > last_progress + step) {
            last_progress += step;
            printf("\r%7.2f%%", last_progress * 100);
            fflush(stdout);
            this_thread::sleep_for(chrono::milliseconds(10));
        }

    }
    return 0;
}

I expect the output to have a single overridable line showing the current progress. If I launch this program in a console everything works as expected. However, when I try to execute it in CLion (2017.1.1) I get the following output:

  10.00%  20.00%  30.00%  40.00%  50.00%  60.00%  70.00%  80.00%  90.00% 100.00%

I've read this thread and I tried disabling putty but it didn't help. This problem has something to do with time in between prints for when I remove the sleep line everything works fine.

QNA
  • 1,047
  • 2
  • 14
  • 26

2 Answers2

1

I accidentally discovered that if you print double \r with some text in between then it starts working.

printf("\rAny text here\r%7.2f%%", last_progress * 100);
QNA
  • 1,047
  • 2
  • 14
  • 26
-2

You are missing \n at the end of your printf argument

arved
  • 4,401
  • 4
  • 30
  • 53
  • No, if I add \n then each line will be printed on a new line. I expect the output to have a _single overridable line_ showing the current progress. This problem exists in CLion only. – QNA Oct 26 '17 at 12:40
  • 1
    sorry, misunderstood your question. have you tried to use `\b` instead? – arved Oct 26 '17 at 12:50
  • Just tried but it didn't help. It works fine in console, but CLion doesn't capture it correctly for some reason. – QNA Oct 26 '17 at 12:58