【问题标题】:C#. How come when I use TextReader.Read() it returns an int value? Possible to convert to char?C#。当我使用 TextReader.Read() 它返回一个 int 值时怎么会?可以转换为char吗?
【发布时间】:2011-09-23 04:23:05
【问题描述】:

所以 TextReader.ReadLine() 返回一个字符串,但 TextReader.Read() 返回一个 int 值。这个 int 值似乎也是某种我不认识的格式。是否可以将此整数转换为字符?感谢您的帮助。

编辑:

TextReader 值 = new StreamReader(@"txt");

    string SValue1;
    int Value1;       
    Value1 = Values.Read();        
    Console.WriteLine(Value1);
    Console.ReadKey();

当它读出值时,它会给我 51 作为输出。 txt文件的第一个字符是3,为什么会这样呢?

【问题讨论】:

标签: c# input char int32 textreader


【解决方案1】:

根据the documentation for the StringReader class(TextReader的子类),Read()的返回值可以转换为char,但需要先检查是否在文件/字符串的末尾(通过检查 -1)。例如,在文档中修改的代码中:

while (true)
{
    int integer = stringReader.Read();

    // Check for the end of the string before converting to a character.
    if (integer == -1)
        break;

    char character = (char) integer; // CONVERT TO CHAR HERE

    // do stuff with character...
}

【讨论】:

  • 感谢帮助 =] 为什么读取的值最初只是一个数字存在?
【解决方案2】:

文档告诉您:如果没有更多数据要读取,则返回 -1,否则返回字符,作为整数。整数不是“某种格式”;整数是原始数据。相反,它是“格式化”的字符;磁盘上的字节必须被解释为字符。

在检查了 -1(它不是一个有效的字符值并且代表流的结束 - 这就是该方法以这种方式工作的原因:因此您可以检查)之后,您可以通过简单的强制转换来转换。

【讨论】:

    【解决方案3】:

    Read 返回一个int o 可以检测到流结束 (-1)。是的,您只需将结果转换为 var c = (int) reader.Read(); 中的字符即可。

    典型用法:

    while (true)
    {
        int x = reader.Read();
        if (x == -1) break;
        char c = (char) x;
        // Handle the character
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      • 2013-01-10
      • 1970-01-01
      • 2018-09-25
      • 2018-05-09
      相关资源
      最近更新 更多