Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
646 views
in Technique[技术] by (71.8m points)

c# - Console.ReadLine add 48 to int

I get 48 when I input 0 to a ReadLine().

Is this a bug?

class Program
{
    static void Main(string[] args)
    {
        string name;
        int age;

        readPerson(out name, out age);
    }
    static void readPerson(out string name, out int age)
    {
        Console.Write("Enter name: ");
        name = Console.ReadLine();
        Console.Write("Enter age: ");
        age = Console.Read();
        Console.WriteLine("Name: {0}; Age: {1}", name, age.ToString());
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, it's not a bug at all.

Console.Read() returns the ASCII character code for whatever character is entered. The ASCII code for the digit 0 is 48, and for the digit 1 is 49, and so on. It's not adding the number 48 arbitrarily, nor does it have anything to do with out parameters.

You need to read in a line and cast the input to an integer accordingly:

Console.Write("Enter age: ");
age = Convert.ToInt32(Console.ReadLine());

If you need to use Read() for whatever reason, then like I said in my comment you need to cast the result to a char. You'll also need to change your variable from int age to char age:

class Program
{
    static void Main(string[] args)
    {
        string name;
        char age;

        readPerson(out name, out age);
    }
    static void readPerson(out string name, out char age)
    {
        Console.Write("Enter name: ");
        name = Console.ReadLine();
        Console.Write("Enter age: ");
        age = (char) Console.Read();
        Console.WriteLine("Name: {0}; Age: {1}", name, age.ToString());
    }
}

Bear in mind that Read() can only read one character at a time, so if you need to parse an age with more than one digit, this won't work, and you're much better off just using ReadLine() instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...