If there is an incorrect user input that was put into the commandline, for example I clear it by using
menu:
answer = Console.ReadLine();
if(!int.TryParse(answer, out val))
{
Console.Clear();
goto menu;
}
However, doing this clears all the console window, what I want to know is that if there is a way to only clear the unwanted/incorrect user input and leave the rest of the Command Line stay the same and uncleared.
CodePudding user response:
The Console class has a method called SetCursorPosition(left, top) that allows you to move the point for the next input in the place you like.
Using this method you can replace the wrong text with an empty string with the same length of the input and then reposition again the cursor to get a new input.
Like so:
static void Main(string[] args)
{
Console.SetCursorPosition(5, 5);
Console.Write("Hello:");
while (true)
{
string input = Console.ReadLine();
if (Int32.TryParse(input, out int val))
{
Console.WriteLine(" Valid input. Exiting ");
break;
}
Console.WriteLine(" Invalid input. Try again");
Console.SetCursorPosition(11, 5);
string delete = new string(' ', input.Length);
Console.Write(delete);
Console.SetCursorPosition(11, 5);
}
}
CodePudding user response:
This code is the generalized solution of my original code in my OP:
int val;
string answer;
var top = Console.CursorTop;
var left = Console.CursorLeft;
menu:
answer = Console.ReadLine();
if (!int.TryParse(cevap, out val))
{
Console.SetCursorPosition(left, top);
Console.Write(new string(' ', answer.Length));
Console.SetCursorPosition(left, top);
goto menu;
}
Using while(true){}
loop, the code above becomes:
top = Console.CursorTop;
left = Console.CursorLeft;
string answer1;
while (true)
{
answer1 = Console.ReadLine();
if (int.TryParse(answer1, out val) || int.Parse(answer1) < 0)
{
break;
}
Console.SetCursorPosition(left, top);
Console.Write(new string(' ', cevap1.Length));
Console.SetCursorPosition(left, top);
}