0
我正在編寫一個類似於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();
}
}
}
}
從我跑了幾個測試,這偉大工程,與真正的文件,但它不確實如預期與標準輸入相當的工作。如果我使用Scanner.Peek
或Scanner.ReadChar
,發送一個新行之後,TextReader
實例認爲這是在文件(我認爲)結束並拋出EndOfStreamException
實例,因爲this.Reader.Read
和this.Reader.Peek
回報-1
。
如何強制它請求一個新的字符,同時還支持真實文件和StringReader
實例?
檢查'-1'和'阻塞'它有什麼問題? – leppie
你的意思是我爲什麼使用try-catch? –