2017-11-25 246 views
-3

我是一個學習.NET的初學者。如何使用console.readline()讀取整數?

我試圖在控制檯readline中解析我的整數,但它顯示一個格式異常。

我的代碼:

using System; 
namespace inputoutput 
{ 
    class Program 
    {   
     static void Main() 
     { 
      string firstname; 
      string lastname; 
     // int age = int.Parse(Console.ReadLine()); 
      int age = Convert.ToInt32(Console.ReadLine()); 
      firstname = Console.ReadLine(); 
      lastname=Console.ReadLine(); 
      Console.WriteLine("hello your firstname is {0} Your lastname is {1} Age: {2}", 
       firstname, lastname, age); 
     } 
    } 
} 
+2

此代碼適用於我。你確定你輸入了第一行的有效整數嗎?也許你可以先將readline放入一個字符串變量,並在解析之前檢查該值? – Chris

+0

可能的重複:https://stackoverflow.com/questions/24443827/reading-an-integer-from-user-input – cSteusloff

+0

是的。它爲我工作。我給了有效的整數。感謝很多 - 格蘭特溫尼 –

回答

1

如果它拋出一個格式異常那麼意味着輸入不能被解析爲int。您可以使用int.TryParse()之類的東西更有效地檢查此問題。例如:

int age = 0; 
string ageInput = Console.ReadLine(); 
if (!int.TryParse(ageInput, out age)) 
{ 
    // Parsing failed, handle the error however you like 
} 
// If parsing failed, age will still be 0 here. 
// If it succeeded, age will be the expected int value. 
0

你的代碼是完全正確的,但你的投入可能不是整數,所以你所得到的錯誤。 嘗試在try catch塊中使用轉換代碼或改用int.TryParse。

+1

它的工作給出一個有效的整數。謝謝 –

+0

TryPars更好,更少開銷 – Sybren

-2

您可以將數字輸入字符串的整數(你的代碼是正確的):

int age = Convert.ToInt32(Console.ReadLine()); 

,如果您處理文本輸入試試這個:

int.TryParse(Console.ReadLine(), out var age); 
+1

這實際上就是問題的代碼。它如何回答這個問題? – UnholySheep

+0

它已被寫入有問題的原始代碼。 – lucky

+0

這就是C#7.0並且工作正常。 – cSteusloff

0

你可以處理無效的格式,除了像這樣的整數;

 int age; 
     string ageStr = Console.ReadLine(); 
     if (!int.TryParse(ageStr, out age)) 
     { 
      Console.WriteLine("Please enter valid input for age ! "); 
      return; 
     }