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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…