当输入 two/more 数字时, Console.Read() 是否将第一个数字作为输入?

Does Console.Read() takes the first digit as input when a two/more digit number as entered?

我是 C# 新手。所以,我通过写一些简单的代码来练习。 我决定编写一段代码,用户将在其中输入一个数字,并将相同的数字显示为输出。我写了下面的代码,它运行得很好。

但是,当我决定用 Console.Read() 替换 Console.Readline() 以查看输出结果和 运行 代码时,我发现输出是我输入的号码第一位的 ASCII 码。 [也就是我输入46的时候,输出的是52。]

然而,当我使用 Console.ReadLine() 时,显示了完整的两位数。

按照我的说法,难道 Console.Read() 只显示输入数字的第一位,而 Console.ReadLine() 显示整个数字吗?

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            int num1;
            Console.Write("Enter a number:");
            num1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("The number is: " + num1);
            Console.ReadKey();

        }
    }
}

根据文档,Console.Read returns:

The next character from the input stream, or negative one (-1) if there are currently no more characters to be read.

作为 int.

int是读取的字符的ASCII值。您只需转换为 char 即可获得字符:

int characterRead = Console.Read();
if (characterRead != -1) {
    char c = (char)characterRead;

    // if you want the digit as an int, you need
    int digit = Convert.ToInt32(c.ToString());
}

另外,请注意,第二次调用 Console.Read 将读取第二个数字。如果你想跳过这个,你需要调用 Console.ReadLine 来清除所有未读的内容。