Why doesn't Console.Read() return the number e

2019-01-20 07:21发布

this is my program that i wrote in C# in visual studio 2010 Ultimate and 2008 Team System:

class Program
{
    static void Main(string[] args)
    {
        int a=0;
        Console.WriteLine("Enter a number: ");
        a = Console.Read();
        Console.WriteLine("you Entered : {0}",a);
        Console.ReadKey();
     }
}

And this is the result:

Enter a number: 5 you Entered : 53

How this possible?

5条回答
该账号已被封号
2楼-- · 2019-01-20 07:32

As the documentation clearly states, Read() returns the index of the Unicode codepoint that you typed.

查看更多
Rolldiameter
3楼-- · 2019-01-20 07:41

Try this to reach your goal:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter a number: ");
        ConsoleKeyInfo a = Console.ReadKey();
        Console.WriteLine("you Entered : {0}",a.KeyChar);
        Console.ReadKey();
     }
}
查看更多
爷、活的狠高调
4楼-- · 2019-01-20 07:50

I'm new to C#, but as far as I know, it's unnecessary to initialize your variable a when you create it. Another way to write your code could be:

class Program
{
    static void Main(string[] args)
    {
        int a;
        Console.WriteLine("Enter a number: ");
        a = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("you Entered : {0}", a);
        Console.ReadKey();
     }
}
查看更多
闹够了就滚
5楼-- · 2019-01-20 07:52

Converted to a character code. Try:

a = int.Parse(Console.ReadLine());
查看更多
仙女界的扛把子
6楼-- · 2019-01-20 07:57

The behavior you observed is described in the documentation.

enter image description here

查看更多
登录 后发表回答