Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a value in a different position via ReadLine in C#?

I would like to ask the user for his/her weight; for example;

Console.Write("Please enter your weight: {I want it to be inserted here} kg");

Here the input will be inserted after the kg, although I want it to be just before "kg" so that the user may know that a kg value is being expected, and that further details are not necessary (such as kg/lbs..)

Thanks in advance.

like image 820
Mohamed Avatar asked Feb 28 '17 13:02

Mohamed


Video Answer


2 Answers

You will have to read every single key the user inputs and then set the cursorposition to the location you want the users weight to be displayed. Afterwards you write it to the console.

static void Main(string[] args)
{
    string prompt = "Please enter your weight: ";
    Console.Write(prompt + " kg");
    ConsoleKeyInfo keyInfo;
    string weightInput = string.Empty;
    while ((keyInfo = Console.ReadKey()).Key != ConsoleKey.Enter)
    {
        //set position of the cursor to the point where the user inputs wight
        Console.SetCursorPosition(prompt.Length, 0);
        //if a wrong value is entered the user can remove it
        if (keyInfo.Key.Equals(ConsoleKey.Backspace) && weightInput.Length > 0)
        {
            weightInput = weightInput.Substring(0, weightInput.Length - 1);
        }
        else
        {
            //append typed char to the input before writing it
            weightInput += keyInfo.KeyChar.ToString();
        }
        Console.Write(weightInput + " kg ");
    }

    //process weightInput here
}
like image 167
lunardoggo Avatar answered Sep 30 '22 05:09

lunardoggo


I've found a simple answer:

Console.Write("enter weight =   kg");
Console.SetCursorPosition(0, 8);
metric.weightKgs = byte.Parse(Console.ReadLine());

It all comes down to cursor positioning and playing around with it finding the exact location.

like image 37
Mohamed Avatar answered Sep 30 '22 04:09

Mohamed