0

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

但是,当我决定将 Console.Readline() 替换为 Console.Read() 以查看输出内容并运行代码时,我发现输出是我输入的数字的第一个数字的 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();

        }
    }
}
4

1 回答 1

0

从文档中,Console.Read返回:

输入流中的下一个字符,如果当前没有要读取的字符,则为负数 (-1)。

作为一个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来清除所有未读的内容。

于 2018-06-05T07:07:26.840 回答