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

只谈情不闲聊 提交于 2019-11-30 10:10:11

问题


I'm a beginner who is learning .NET.

I tried parsing my integer in console readline but it shows a format exception.

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

回答1:


If it's throwing a format exception then that means the input isn't able to be parsed as an int. You can check for this more effectively with something like 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.



回答2:


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.




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/47485791/how-to-read-an-integer-using-console-readline

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!