2017-11-25 164 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; 
     } 
相关问题