简体   繁体   English

如何使用console.readline()读取整数?

[英]How to read an integer using console.readline()?

I'm a beginner who is learning .NET.我是一个正在学习 .NET 的初学者。

I tried parsing my integer in console readline but it shows a format exception.我尝试在控制台 readline 中解析我的整数,但它显示格式异常。

My code:我的代码:

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);
        }
    }
}

If it's throwing a format exception then that means the input isn't able to be parsed as an int .如果它抛出格式异常,则意味着输入无法解析为int You can check for this more effectively with something like int.TryParse() .您可以使用int.TryParse()类的int.TryParse()更有效地检查这一点。 For example:例如:

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.

Your code is absolutely correct but your input may not be integer so you are getting the errors.您的代码绝对正确,但您的输入可能不是整数,因此您会收到错误消息。 Try to use the conversion code in try catch block or use int.TryParse instead.尝试使用 try catch 块中的转换代码或使用 int.TryParse 代替。

You can handle invalid formats except integer like this;您可以像这样处理除整数之外的无效格式;

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

You can convert numeric input string to integer (your code is correct):您可以将数字输入字符串转换为整数(您的代码是正确的):

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

If you would handle text input try this:如果您要处理文本输入,请尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM