2017-02-28 27 views
5

我想問用戶他/她的體重;例如;如何通過C#中的ReadLine在不同的位置插入值?

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

這裏,輸入將被插入公斤之後,雖然我希望它只是「公斤」之前,所以用戶可以知道,一公斤值被預期,以及進一步的細節是沒有必要的(如千克/磅..)

在此先感謝。

+2

我想這是不可能的。你可以寫下「請輸入你的體重(千克):」以說明他必須輸入體重的單位。 –

+2

控制檯輸入不會格式漂亮,只需執行ReadLine()並處理字符串。 –

回答

1

你需要寫控制檯您的問題(我會做這樣的)

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

然後等待值回來。

這將等待用戶

string userInput = Console.ReadLine(); 

使用一個美元符號的字符串允許串插。根據您的C#版本,這可能不起作用。

Console.WriteLine($"Your weight is {userInput}kg."); 
+0

如果因爲使用美元符號進行字符串插值而無法工作,請執行以下操作:Console.Write(「您的體重是」+ userInput +「kg」); 我也建議Console.WriteLine代替Console.Write這個特殊的實例。 https://msdn.microsoft.com/en-us/library/zdf6yhx5(v=vs.110).aspx –

+0

請注意maximelian 1986的答案。您不能將Console.ReadLine的結果存儲在一個整數中。 –

-1
int weight = Console.ReadLine(); 
if (weight != null) 
Console.WriteLine(string.format("Please enter your weight: {1} kg", weight)); 

這是未經檢查的代碼。但應該是這樣的。

+1

我不明白整數如何爲空。而在string.Format中,它必須是{0}在這裏,而不是{1} ... – Kzrystof

3

您必須閱讀用戶輸入的每個單鍵,然後將光標位置設置爲您希望顯示用戶體重的位置。之後,您將其寫入控制檯。

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 
} 
+2

我更喜歡這種解決方案,因爲您可以檢查每個數字的輸入。所以不可能寫'abc kg'。如果你想知道kg後的空間,那麼這是清理最後一個字符的方法,其他的方法是在一段時間後它會是'70 kgggg' – Matt

2

我發現一個簡單的答案:

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

這一切都歸結到光標的定位和它找到確切位置玩耍。

相關問題