Ryan
Ryan

Reputation: 1791

Wrong output for console .NET

Why the output is not what I want to...

Here's the code:

int num;
Console.WriteLine("Please input age: ");
num = Console.Read();
Console.WriteLine(num);

For example I input 5, the output is 53. It needs to be 5, what is happening on the code. Can somebody explain? Thank you.

Upvotes: 0

Views: 166

Answers (2)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133014

Because Console.Read() returns the character code of the next character in the stream. The ASCII character code of '5' is 53.

You need to read the whole line as a string

string str = Console.Readline();

and then Parse() it or TryParse() it.

 int num;
 try
 {  
     num = int.Parse(str);
 }
 catch(Exception e)
 {
     Console.Writeline("Not a number!");
 }

Upvotes: 8

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

According to the documentation of the Read method:

Reads the next character from the standard input stream.

So this will returns the ASCII value of a single character that the user entered.

You need to read the entire line and parse the string back to an integer:

int num;
Console.WriteLine("Please input age: ");
num = int.Parse(Console.ReadLine());
Console.WriteLine(num);

of course this parsing might fail if the user enters an invalid integer. So you could handle it like this:

int num;
Console.WriteLine("Please input age: ");
if (!int.TryParse(Console.ReadLine(), out num))
{
    Console.WriteLine("Please enter a valid age");
}
else
{
    Console.WriteLine(num);
}

Upvotes: 4

Related Questions