0

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.

1
  • 5
    Is there some relation between this example and a fact that you study ASP.NET ? If yes, please explain. Commented Jul 10, 2011 at 10:30

2 Answers 2

8

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!");
 }
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.