C# Console.read() 未显示正确的数字输入

本文关键字:数字输入 显示 Console read | 更新日期: 2023-09-27 18:34:37

 String name = Console.ReadLine();
            System.Console.WriteLine("input name");
            System.Console.WriteLine("hello {0}", name);
            int hello = Console.Read();
            System.Console.WriteLine("First number input" + hello);
            int hello2 = Console.Read();
            Console.ReadKey();
            System.Console.WriteLine("Second number input" + hello2);

在这一行代码中,它显示输入的名称,然后显示第二个键的第一个键(即 hello(的输入,但无论我做什么,它总是显示为 13。我该如何解决这个问题?

C# Console.read() 未显示正确的数字输入

Console.Read不会解析输入字符。 它返回一个整数是误导性的,但这实际上是输入的单个字符的数字表示形式。

相反,请使用 Console.ReadLine ,并将结果解析为数字。

int hello;
while(!int.TryParse(Console.ReadLine(), out hello)
{
   // This will happen if the user types something that's not a number
   Console.WriteLine("Please enter a valid number:"); 
}
Console.WriteLine("First number input" + hello);

你可以这样修改: //assumed you want to get integer values String name = Console.ReadLine(); System.Console.WriteLine("input name"); System.Console.WriteLine("hello {0}", name); int hello = Convert.ToInt16(Console.ReadLine()); System.Console.WriteLine("First number input" + hello); int hello2 = Convert.ToInt16(Console.ReadLine()); Console.ReadKey(); System.Console.WriteLine("Second number input" + hello2);

我发现了您的代码的一些基本问题,并将我的想法放在下面的评论中。

String name = Console.ReadLine(); // Shows the cursor without a prompt to the user
System.Console.WriteLine("input name");
System.Console.WriteLine("hello {0}", name);
int hello = Console.Read(); // This line reads the new line character (13) from the above line
System.Console.WriteLine("First number input" + hello); // Displays 13 (new line character if the user doesn't enter any value)
int hello2 = Console.Read();
Console.ReadKey(); // Exits the console as soon as a user press a key
System.Console.WriteLine("Second number input" + hello2); // This is never displays to the user

我想在向您展示所有问题后重新考虑它。这是我想到的。看一看。由于您正在尝试使用用户输入构建一个简单的应用程序,因此还必须考虑用户输入和输出的流。

int firstNumber;
int secondNumber;
string name = string.Empty;
do
{
    Console.Clear();
    Console.Write("What is your name?");
    name = Console.ReadLine();        
} while (string.IsNullOrEmpty(name));
Console.WriteLine("Hello {0}", name);
do
{
    // This will happen if the user types something that's not a number
    Console.Clear();
    Console.WriteLine("Hello {0}", name);
    Console.Write("Please enter the first number:");
} 
while (!int.TryParse(Console.ReadLine(), out firstNumber));
do
{
    // This will happen if the user types something that's not a number
    Console.Clear();
    Console.WriteLine("Hello {0}", name);
    Console.WriteLine("First number is: " + firstNumber);
    Console.Write("Please enter the second number:");
}
while (!int.TryParse(Console.ReadLine(), out secondNumber));
Console.WriteLine("Second number is: " + secondNumber);
Console.Read();