Akshdeep Singh
Akshdeep Singh

Reputation: 1447

How to update values in printed output only in C?

I want to print a line:

for(i=0;i<n;i++)
   printf("this is iteration number %d\n", i);

From this I will get output as:

this is iteration number 0

this is iteration number 1

...

But I want that only one line is printed and the value changes. That is I want to overwrite each line.

Now if I print some another line (lets call it line2) but I need to overwrite the previous line without affecting the line2.

Upvotes: 2

Views: 759

Answers (2)

Viktor Holm&#233;r
Viktor Holm&#233;r

Reputation: 59

You can use a carriage return \r to return the cursor to the front of the line and then overwrite it in the next iteration:

int n = 100;
for (int i = 0; i < n; i++) {
    printf("\rThis is iteration number %d", i);
    fflush(stdout);
    sleep(1);
}

Upvotes: 1

Sigve Karolius
Sigve Karolius

Reputation: 1456

Not the most refined solution, but you can use a "carriage return" \r and flush stdout like this:

#include <stdio.h>
#include <unistd.h>
int main() 
{
  for (int i = 0; i < 10; i++) {
      printf("\rValue of i is: %d", i);
      fflush(stdout);
      sleep(1);
  }
}

Upvotes: 3

Related Questions