2012-12-26 37 views
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.PeekScanner.ReadChar,發送一個新行之後,TextReader實例認爲這是在文件(我認爲)結束並拋出EndOfStreamException實例,因爲this.Reader.Readthis.Reader.Peek回報-1

如何強制它請求一個新的字符,同時還支持真實文件和StringReader實例?

+0

檢查'-1'和'阻塞'它有什麼問題? – leppie

+0

你的意思是我爲什麼使用try-catch? –

回答

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