当没有字符保留时,如何从stdin读取?

时间:2012-12-26 22:24:39

标签: c# .net stdin textreader

我正在编写一个类似于Java的基本Scanner类。这就是我所拥有的(以及相关部分):

using System.Text;
using System.Collections.Generic;

namespace System.IO
{
    /// <summary>
    ///     <remarks>
    ///         Scanner is a wrapper for a <see cref="System.IO.TextReader" />
    ///         instance, making it easier to read values of certain types. It
    ///         also takes advantage of the
    ///         <see cref="System.IO.EndOfStreamException" /> class.
    ///     </remarks>
    ///     <seealso cref="System.IO.TextReader" />
    /// </summary>
    public class Scanner
    {
        private TextReader Reader;
        private Queue<char> CharacterBuffer = new Queue<char>();

        /// <summary>
        ///     <remarks>
        ///         Defaults to reading from <see cref="Console.In"/>
        ///     </remarks>
        /// </summary>
        public Scanner() : this(Console.In)
        {
        }

        public Scanner(TextReader reader)
        {
            this.Reader = reader;
        }

        public char Peek()
        {
            if (this.CharacterBuffer.Count > 0)
                return this.CharacterBuffer.Peek();

            try
            {
                return Convert.ToChar(this.Reader.Peek());
            }
            catch (OverflowException)
            {
                throw new EndOfStreamException();
            }
        }

        public char ReadChar()
        {
            if (this.CharacterBuffer.Count > 0)
                return this.CharacterBuffer.Dequeue();

            try
            {
                return Convert.ToChar(this.Reader.Read());
            }
            catch (OverflowException)
            {
                throw new EndOfStreamException();
            }
        }
    }
}

从我运行的几个测试中,这对于真实文件非常有用,但是使用stdin并没有像预期的那样工作。如果我使用Scanner.PeekScanner.ReadChar,则在发送换行符后,TextReader实例认为它位于文件末尾(我认为)并抛出EndOfStreamException个实例自this.Reader.Readthis.Reader.Peek返回-1

如何在仍然支持真实文件和StringReader个实例的同时强制它请求新角色?

1 个答案:

答案 0 :(得分:0)

我更改了Peek以反映以下代码。我不确定这是100%,因为我直接从内存中输入了这个。

public char Peek()
{
    if (this.CharacterBuffer.Count > 0)
        return this.CharacterBuffer.Peek();

    char Character
    try
    {
        Character = Convert.ToChar(this.Reader.Read());
    }
    catch (OverflowException)
    {
        throw new EndOfStreamException();
    }

    this.CharacterBuffer.Enqueue(Character);
    return Character;
}