Question How to remove/delete a string that has been just entered by a user and read by console from Console Interface Screen?

Joined
Sep 26, 2022
Messages
16
Programming Experience
1-3
I want to delete a user input if a condition is not met, and keep the Console interface same and intact without using Console.Clear() or goto menu;
1668878424065.png

I want to delete whatever was entered by the user if a condition is not met. How can I do that?

If I use Console.Clear() or goto menu; the same code repeats over and over again and it makes the app slow and exhausting to code.
 
Why would you use goto menu to try to control the console? Why do you even have goto's in your code. goto's should only be used as a last resort when the normal looping and branching structures won't work. Can you share your current code?

Anyway, if you look at the Console class documentation, you can control the cursor position. So remember the cursor position before you ask for input. Then after you get the input, move the cursor back to the same position, write out spaces equal to the length of the input to overwrite the user's input, and finally move the cursor to the same position again. You will need to add extra logic to handle if the screen scrolls while the user is entering their input.
 
If there is an incorrect user input that was put into the commandline, for example I clear it by using

C#:
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.
 
Last edited by a moderator:
In your code in post #3, it is not the goto menu that is clearing the screen. It is the call to Console.Clear() which is clearing the screen. The goto menu just makes your code loop back to get the input again.

That code could have been written without goto:
C#:
while (true)
{
    var input = Console.ReadLine();
    if (int.TryParse(input, out val))
        break;
    Console.Clear();
}

Anyway, see my second paragraph in post #2, about how to clear parts of the console screen on Windows.
 
Back
Top Bottom