0

In the example below, assuming the user enters a negative number, how can I bring the cursor back to the same place where the user entered an invalid number so that the program can continue on?

Console.Write("Enter a number for the factorial: ");

int k = Convert.ToInt32(Console.ReadLine());

if (k < 0)
{
    Console.WriteLine("Please enter a number that is greater than or equal to zero");
}
a sandwhich
  • 4,352
  • 12
  • 41
  • 62

2 Answers2

0

i think this will meet your requirement

string errormessage="Please enter a positive number; previous input was invalid";
        Console.WriteLine("Enter the number: ");
        int k = Convert.ToInt32(Console.ReadLine());
        while (k < 0)
        {
            Console.Write(errormessage);
            //get back to the input line
            Console.SetCursorPosition(0, Console.CursorTop-1);
            //Clearing the previous input
            for (int i = 0; i < k.ToString().Length; i++)
                Console.Write(" ");
            Console.Write("\r");
            k = Convert.ToInt32(Console.ReadLine());
        }
        //Clearing the error message
        for (int i = 0; i < errormessage.Length; i++)
            Console.Write(" ");
        Console.WriteLine("\r");

sorry not the prettiest of code but does the job!

Nithin Nayagam
  • 458
  • 2
  • 5
  • 9
0

Utilizing the methods in this similar post, I believe you can solve your issues. Basically just copy the ClearConsoleLine method and use the Console.SetCursorPosition to move to the desired line/column.

Community
  • 1
  • 1
maccettura
  • 10,514
  • 3
  • 28
  • 35