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

I would like to ask the user for his weight; eg,

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

Here the input will be inserted after the kilogram, although I want it to be immediately before the โ€œkgโ€, so that the user can know that the kilogram value is expected and that further details are not needed (for example, kg / lbs ..)

Thanks in advance.

+5
source share
4 answers

You will need to read each individual key that the user enters, and then set the cursor position in the place where you want the user weight to be displayed. Then you write it on 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 } 
+3
source

I found a simple answer:

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

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

+2
source

You need to write your question to the console (I would do it like this)

 Console.WriteLine("Please enter your weight (kg):"); 

Then wait until the value returns.

This will wait for the user.

 string userInput = Console.ReadLine(); 

Using a dollar sign in a string allows string interpolation. Depending on your version of C #, this may not work.

 Console.WriteLine($"Your weight is {userInput}kg."); 
+1
source
 int weight = Console.ReadLine(); if (weight != null) Console.WriteLine(string.format("Please enter your weight: {1} kg", weight)); 

This is unverified code. But there must be something like that.

-1
source

Source: https://habr.com/ru/post/1264834/


All Articles