0

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

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();
            }
        }
    }
}

从我运行的几个测试来看,这对真实文件非常有效,但对于标准输入,它并不像预期的那样有效。如果我使用Scanner.Peekor Scanner.ReadChar,在发送换行符后,该TextReader实例认为它位于文件末尾(我认为)并抛出一个EndOfStreamException实例 sincethis.Reader.Readthis.Reader.Peek返回-1.

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

4

1 回答 1

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;
}
于 2013-01-20T16:43:05.870 回答