1

I'm trying to modify a variable in the console automatically without modifying the rest of the text. To do this I've already tried to make an infinite loop that erases the console and notices all the lines but it creates a fluidity problem so I'm looking for a way to modify only the variables without touching the rest of the console.

int total = 10000;
int remaining = remaining - total;

Console.WriteLine("Remaining : " + remaining"); <---- Here I want to modify the remaining variable without having to clear the console
Fanfarone
  • 131
  • 1
  • 7
  • The proper title seems to be "overwrite a alraedy written line in console". This thing is a finicky thing. And the kind of thing, that should be finally burried as a bad idea. You are trying to do an operation the console was never desigend for and that is extremely easy to get wrong. If you want that level of Display fidelity, you should just be going for WindowsForms or WPF already. – Christopher Dec 07 '19 at 12:36

1 Answers1

2

You can overwrite the console buffer on that said position:

using System;

            var numberVariable = 1;
            var text = "Hello World Times " + numberVariable;
            while (true)
            {
                Thread.Sleep(500);
                //writes the text into 0|0
                Console.WriteLine(text);
//LOOPBEGIN
//The cursor is now on 0|1
//Console.WriteLine advances the cursor to the next line so we need to set it to the previous line
//Ether by:
//Console.SetCursorPosition(0 /**Column 0**/, Console.CursorTop - 1);
//or by
                Console.CursorTop = Console.CursorTop - 1;
                Console.CursorLeft = 0;
//The cursor is now again on 0|0
                numberVariable = numberVariable + 1;
//increment the variable
                text = "Hello World Times " + numberVariable;
//ether set the text variable again or use a new variable
            }

https://learn.microsoft.com/de-de/dotnet/api/system.console.setcursorposition?view=netframework-4.8

Venson
  • 1,772
  • 17
  • 37
  • I tried in an infinite loop with variable + 10 but it doesn't work, it always writes the same thing – Fanfarone Dec 07 '19 at 12:57
  • @FanTaZyyf i updated the example code to include an infinite loop. Tested it, works like a charm. The provided link includes an MSDN example for a waiter have you checkt that out? – Venson Dec 08 '19 at 11:02