0

I have a C# console program that asks the user for a certain word by showing a input prompt. The input is then processed using an switch statement. If the word is correct, the program continues. But if the input doesn't match, the program says "Error: invalid input" and then goes back to the input prompt. The tricky part is that I want the program to clear the input that the user just typed before pressing Enter and prompt the user again, without making another separate prompt below the first one.

Is there a library of some kind in C# that does something like that, or do I have to make a library for it?

S. Ferrell
  • 171
  • 3
  • 11
  • 1
    Kindly read this post: [Can Console.Clear be used to only clear a line instead of whole console?](https://stackoverflow.com/questions/8946808/can-console-clear-be-used-to-only-clear-a-line-instead-of-whole-console) – Zuhair Oct 29 '18 at 23:18
  • It would be helpful to see the code you currently have (that's relevant to this question). – Rufus L Oct 29 '18 at 23:41
  • Pro Tip, There is a reason we don't write code in natural language. because natural language is ambiguous and not precise. In short we need to see your code not a description, empirical evidence and concrete examples 99 times out of 100. Anything else makes it hard for us – TheGeneral Oct 30 '18 at 00:05

2 Answers2

2

One way to do this is to use a combination of Console.SetCursorPosition and Console.Write to set the cursor to the beginning of their response, write enough whitespace to "erase" their reaponse, and then set the cursor back to the beginning again.

For example:

static string GetUserInput(string prompt, List<string> validResponses)
{
    Console.Write(prompt);

    // Capture the cursor position just after the prompt
    var inputCursorLeft = Console.CursorLeft;
    var inputCursorTop = Console.CursorTop;

    // Now get user input
    string input = Console.ReadLine();

    while (validResponses != null &&
           validResponses.Any() &&
           !validResponses.Contains(input, StringComparer.OrdinalIgnoreCase))
    {

        Console.ForegroundColor = ConsoleColor.Red;
        // PadRight ensures that this line extends the width
        // of the console window so it erases itself each time
        Console.Write($"Error! '{input}' is not a valid response".PadRight(Console.WindowWidth));
        Console.ResetColor();

        // Set cursor position to just after the promt again, write
        // a blank line, and reset the cursor one more time
        Console.SetCursorPosition(inputCursorLeft, inputCursorTop);
        Console.Write(new string(' ', input.Length));
        Console.SetCursorPosition(inputCursorLeft, inputCursorTop);

        input = Console.ReadLine();
    }

    // Erase the last error message (if there was one)
    Console.Write(new string(' ', Console.WindowWidth));

    return input;
}

In use this might look like:

static void Main(string[] args)
{
    var validResponses = new List<string> {"Yes", "No"};

    var userInput = GetUserInput("Do you like me? ", validResponses);

    if (userInput.Equals("Yes", StringComparison.OrdinalIgnoreCase))
    {
        Console.WriteLine("I like you too!");
    }
    else
    {
        Console.WriteLine("And all along I thought you had good taste.");
    }

    GetKeyFromUser("\nDone! Press any key to exit...");
}

Here's a sample run of the program. I had to include several screenshots since the response (and then the error message) are cleared on each iteration:

enter image description here

Rufus L
  • 36,127
  • 5
  • 30
  • 43
0

Try this ...

static void Main(string[] args)
{

CheckWord();
Console.ReadKey();
}

    private static void CheckWord()
    {
        while (true)
        {
            string errorMessage = "Error: invalid input ... enter a valid entry";
            string word = Console.ReadLine(); 
            if (word != "word")
            {
                Console.SetCursorPosition(word.Length +1 , (Console.CursorTop) - 1);
                Console.Write(errorMessage);
                Console.ReadKey();
                Console.SetCursorPosition(0, Console.CursorTop);
                for (int i = 0; i <= word.Length + errorMessage.Length +1 ; i++)
                {
                    Console.Write(" ");
                }
                Console.SetCursorPosition(0, Console.CursorTop);
            }
            else
            {

                break;
            }
        }
    }
A.Marach
  • 1
  • 1