开发者

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, th开发者_如何学Pythone output is 53. It needs to be 5, what is happening on the code. Can somebody explain? Thank you.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜