为什么Convert.ToInt32(Console.Read())返回53而不是5?

问题描述 投票:-1回答:1

此程序:

static void Main(string[] args)
{
    int x;
    Console.Write("Enter number:");
    x = Convert.ToInt32(Console.Read());
    Console.WriteLine($"Output: {x}");
}

控制台文本:

Enter number: 5
Output: 53

Press any key to continue...

截屏:

enter image description here

输入数字5但输出不是5

c#
1个回答
3
投票
  • Console.Read()读取单个字符作为char,而不是整行作为string
  • [char]值本身实际上是整数,对于大多数操作,C#/。NET不会将其处理为文本,这可能会淘汰初学者。
  • '5'的整数值(作为charis 53 in ASCII and Unicode
  • Convert.ToInt32(Char)char值视为整数(因此'5'53),然后将其转换为Int32值,而不是将字符解析为十进制数字。
    • 我强烈建议您避免使用Convert类。 .NET Framework中有更好的替代方法(例如Int32.TryParse)。

要解决此问题,请使用Console.ReadLine()Int32.TryParse而不是Convert.ToInt32,以便可以正常处理无效输入。

while( true )
{
    Console.Write( "Enter number: " );
    String input = Console.ReadLine();
    if( Int32.TryParse( input, out Int32 value ) ) // ideally use the overload with NumberStyles.Any and CultureInfo.CurrentCulture to be explicit.
    {
        Console.WriteLine( $"Output: {value}" );
    }
    else
    {
        Console.WriteLine( "Please enter a valid number." ); 
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.