Update console line with C#

Asked

Viewed 287 times

1

I already asked this same question once, but in that case I needed for the python language, now I need to solve this same problem, with the C language#

I have a loop in C#, and would like to inform the value of a variable each time it is updated, however I don’t want to dirty the console printing every time and or clean the whole console.

There is a way I can get this result?

int a = 0;
Console.WriteLine("Executando processo:");
while (True) {
    a = a +1
    Console.WriteLine(a);
}

The result at the end of 3 interactions is:

Interaction 1:

$ - Executando processo: 
$ - 1 

Interaction 2:

$ - Executando processo:
$ - 1 
$ - 2

Interaction 3:

$ - Executando processo:
$ - 1 
$ - 2
$ - 3

And I would like to get the following result:

Interaction 1:

$ - Executando processo:
$ - 1 

Interaction 2:

$ - Executando processo:
$ - 2

Interaction 3:

$ - Executando processo:
$ - 3 

1 answer

2


You can use the Console.Write printing on the same line. I made use of the Setcursorposition setting the cursor position on the screen.

a = a + 1;
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write("{0}", a);
Thread.Sleep(1000);
  • Great, with the version you put before, with the " r", solved my problem very well, I just still can’t quite understand how this escape character works. The Console.Setcursorposition also worked

  • r corresponds to a return cursor

Browser other questions tagged

You are not signed in. Login or sign up in order to post.