Console.Read() 直到 eof

Console.Read() until eof

我必须从控制台读取以白色字符分隔的整数,直到文件结尾,但我不知道如何,我搜索答案但找不到。

while((x = Console.Read()) != null)

int 值不可为空。你必须使用负数。

while((x = Console.Read()) != -1)

Note that the method does not return -1 unless you perform one of the following actions:

  • Simultaneously press the Control modifier key and Z console key (Ctrl+Z), which signals the end-of-file condition.
  • Press an equivalent key that signals the end-of-file condition, such as the F6 function key in Windows.
  • Redirect the input stream to a source, such as a text file, that has an actual end-of-file character.

MSDN Read() method.

然后您可以按字符读取文件并使用简单的数学计算每个分隔值。它很懒惰,不会立即将文件迭代到末尾以计算所有值。

static void Main(string[] args)
{
    foreach (int i in Read(Console.In))
    {
        Console.WriteLine(i);
    }
}

static IEnumerable<int> Read(TextReader rdr)
{
    int ch;
    bool neg = false;
    int value = 0;
    int count = 0;

    while ((ch = rdr.Read()) != -1)
    {
        if (char.IsWhiteSpace(ch))
        {
            if (count > 0)
                yield return neg ? -value : value;  
            count = 0;
            value = 0;
            neg = false;
        }
        else if (count == 0 && ch == '-')
        {
            neg = true;
        }
        else if (ch >= '0' && ch <= '9')
        {
            count++;
            value = value*10 + (ch - '0');
        }
        else
            throw new InvalidDataException();
    }

    if (count > 0)
        yield return neg ? -value : value;  
}