【问题标题】:Console.Read() and Console.ReadLine() problems [duplicate]Console.Read() 和 Console.ReadLine() 问题[重复]
【发布时间】:2012-08-31 17:55:08
【问题描述】:

我一直在尝试在 C# 中使用 Console.Read() 和 Console.ReadLine(),但得到了奇怪的结果。例如这段代码

Console.WriteLine("How many students would you like to enter?");
int amount = Console.Read();
Console.WriteLine("{0} {1}", "amount equals", amount);

for (int i=0; i < amount; i++)
{
     Console.WriteLine("Input the name of a student");
     String StudentName = Console.ReadLine();
     Console.WriteLine("the Students name is " + StudentName);
}

当我输入 1 作为学生人数时,一直给我这个数量 = 49,我什至没有机会输入学生姓名。

【问题讨论】:

标签: c# .net console-application


【解决方案1】:

这是因为您读取了一个字符。 使用适当的方法(如 ReadInt32())负责将读取的符号正确转换为您想要的类型。

你得到49的原因是因为它是'1'符号的字符代码,而不是它是整数表示。

char     code
0 :      48
1 :      49
2:       50
...
9:       57

例如:ReadInt32() 可以是这样的:

public static int ReadInt32(string value){
      int val = -1;
      if(!int.TryParse(value, out val))
          return -1;
      return val;
}

并像这样使用:

int val = ReadInt32(Console.ReadLine());

如果有可能创建extension method 会非常好,但不幸的是,无法在静态类型上创建扩展方法,而Consolestatic 类型。

【讨论】:

  • int.TryParse 足够简单,您的ReadInt32 方法的元素在调用方法中被重用,您最好使用Rune FS 或Steve 提出的解决方案。
  • @Trisped:如果在程序流程中发生我需要从控制台读取多次integer,我希望将它放在单个方法中,然后调用 method,而不是到处都是意大利面条代码。
  • 如果您使用您的方法写出整个代码块,您会发现您使用相同数量的变量和方法调用(因为您必须验证输入),就像您刚刚使用 @ 987654333@ 方法。如果还有更多内容,那么只需将字符串转换为 int,那么我会同意,因为将代码放在一种方法中而不是分布在所有使用它的地方会更容易/更安全。
【解决方案2】:

Console.Read() 正在返回您输入的字符的字符代码。您需要使用Convert.ToChar(amount); 将字符作为字符串获取,然后您需要使用int.Parse() 来获取您要查找的值。

【讨论】:

    【解决方案3】:

    尝试以这种方式更改您的代码

    int amount;
    while(true)
    {
        Console.WriteLine("How many students would you like to enter?"); 
        string number = Console.ReadLine(); 
        if(Int32.TryParse(number, out amount))
            break;
    }
    Console.WriteLine("{0} {1}", "amount equals", amount); 
    for (int i=0; i < amount; i++) 
    { 
        Console.WriteLine("Input the name of a student"); 
        String StudentName = Console.ReadLine(); 
        Console.WriteLine("the Students name is " + StudentName); 
    } 
    

    而不是使用Read 使用ReadLine,然后使用Int32.TryParse 检查用户输入是否真的是整数。如果用户未输入有效数字,请重复该问题。
    使用 Console.Read 会将您的输入限制为需要转换并检查为有效数字的单个字符。

    当然,这是一个残酷的例子,没有任何错误检查或任何形式的安全中止循环。

    【讨论】:

    • 如果他希望用户能够只输入一个字符而不是输入一整行怎么办?
    • 但这会将学生人数限制在 9 人之内。而且我在任何地方都没有读过这个要求。
    • 他似乎特意不使用ReadLine,这表明他只想要一个数字。
    • @Trisped 好吧,很明显他不知道Read 是如何工作的。更多的是一个问题,“Read 他误会了吗?”
    【解决方案4】:

    你从读取而不是 int 中得到一个字符 char。您需要先将其设为字符串并将其解析为字符串。实现可能如下所示

        Console.WriteLine("How many students would you like to enter?");
        var read = Console.ReadLine();
        int amount;
        if(int.TryParse(read,out amount)) {
          Console.WriteLine("{0} {1}", "amount equals", amount);
    
          for (int i=0; i < amount; i++)
          {
            Console.WriteLine("Input the name of a student");
            String StudentName = Console.ReadLine();
            Console.WriteLine("the Students name is " + StudentName);
          }
        }
    

    我已将其更改为使用 readline,因为 readline 返回一个字符串并且不会任意将学生人数限制为 9(一位数的最大人数)

    【讨论】:

    • 感谢大家的帮助,程序现在似乎运行良好
    【解决方案5】:

    代替:

    int amount = Console.Read();
    

    尝试:

    int amount = 0;
    int.TryParse(Console.ReadLine(), out amount);
    

    这是因为您只读取字符代码,因此例如输入 11 您仍然会得到 49。您需要读取字符串值并将其解析为 int 值。使用上面的代码,如果输入错误,您将得到 0。

    【讨论】:

      【解决方案6】:

      Console.Read 返回按下的键字符的 asci 值。

      如果你使用Console.ReadKey().KeyChar,你会得到一个char,它代表被按下的实际字符。

      然后您可以使用.ToString() 将该字符转换为一个字符串。

      现在您有了一个字符串,您可以使用int.Parseint.TryParse 将一个完全包含数字字符的字符串转换为一个整数。

      所以把它们放在一起:

      int value;
      if (int.TryParse(Console.ReadKey().KeyChar.ToString(), out value))
      {
          //use `value` here
      }
      else
      {
          //they entered a non-numeric key
      }
      

      【讨论】:

        【解决方案7】:
        Console.WriteLine("How many students would you like to enter?");
        string amount = Console.ReadLine();
        int amt = Convert.ToInt32(amount);
        
        Console.WriteLine("{0} {1}", "amount equals", amount);
        
        for (int i = 0; i < amt; i++)
        {
            Console.WriteLine("Input the name of a student");
            String StudentName = Console.ReadLine();
            Console.WriteLine("the Students name is " + StudentName);
        }
        //thats it
        

        【讨论】:

          【解决方案8】:

          试试这个:

          int amount = ReadInt32();
          

          或者如果它不起作用,试试这个:

          int amount = Console.ReadInt32();
          

          或者这个:

          int amount = Convert.ToInt32(Console.Readline());
          

          在此,它将读取字符串,然后将其转换为 Int32 值。

          你也可以去这里:http://www.java2s.com/Tutorials/CSharp/System.IO/BinaryReader/C_BinaryReader_ReadInt32.htm

          如果没有任何效果,请告诉我。

          【讨论】:

            【解决方案9】:

            对于可能仍然需要这个的人:

            static void Main(string[] args)
            {
                 Console.WriteLine("How many students would you like to enter?");
                 var amount = Convert.ToInt32(Console.ReadLine());
            
                 Console.WriteLine("{0} {1}", "amount equals", amount);
            
                 for (int i = 0; i < amt; i++)
                 {
                     Console.WriteLine("Input the name of a student");
                     String StudentName = Console.ReadLine();
                     Console.WriteLine("the Students name is " + StudentName);
                 }
            }
            

            【讨论】:

              【解决方案10】:

              TL;DR; Windows 中的 Enter 键不是单个字符。这一事实是与Console.Read() 方法相关的许多问题的根源。

              完整详情: 如果您在计算机上运行以下代码,那么您可以解决Console.Read()背后的许多谜团:

              static void Main(string[] args)
              {
                  var c = Console.Read();
                  Console.WriteLine(c);
                  c = Console.Read();
                  Console.WriteLine(c);
              }
              

              在运行程序时,只需在键盘上按一次 Enter 键,然后检查控制台上的输出。下面是它的外观:

              有趣的是,您只按了一次 Enter 键,但它能够满足我的代码 sn-p 中的两个 Read() 调用。 Windows 中的 Enter 键为换行符发出两个字符,即回车符(\r - ASCII 代码 13)和换行符(\n - ASCII 代码 10)。您可以在这篇文章中了解更多信息 - Does Windows carriage return \r\n consist of two characters or one character?

              【讨论】:

                猜你喜欢
                • 2013-08-23
                • 1970-01-01
                • 2011-10-13
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多