I want to overwrite the last line in the console for looping a specific row with changes.
For example: I want to print to console . then .. then ...
This my code for that:
int dot = 1;
while (true)
{
switch (dot)
{
case 1:
Console.SetCursorPosition(0, Console.CursorTop-1);
Console.WriteLine(".");
dot++;
Thread.Sleep(500);
break;
case 2:
Console.SetCursorPosition(0, Console.CursorTop -1);
Console.WriteLine("..");
dot++;
Thread.Sleep(500);
break;
case 3:
Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.WriteLine("...");
dot = 1;
Thread.Sleep(500);
break;
}
}
}
My problem is that after the first complete round(after it print the "..." in first time) it not print "." the console stay on "..."
I mean:
now it stay "..." instead remove "..." and print ".".
Someone has idea why?
You're only printing one character when you print a single dot - you're not affecting the rest of the line.
If you just change this:
Console.WriteLine(".");
to
Console.WriteLine(". ");
then it'll remove any characters written by previous iterations. (That still won't clear anything else on the line though.)
(You may want to change the Console.WriteLine("..")
to Console.WriteLine(".. ")
for consistency but it won't make a difference as you've already printed the final space in the previous iteration.)
Note that you can remove repetition fairly simply too:
string[] dots = { ". ", "..", "..." };
int index = 0;
while (true)
{
Console.SetCursorPosition(0, Console.CursorTop -1);
Console.WriteLine(dots[index]);
index = (index + 1) % 3;
Thread.Sleep(500);
}
See more on this question at Stackoverflow