Need help with Read() function

Discussion in 'C#' started by vlado_036, Oct 24, 2009.

  1. vlado_036

    vlado_036 New Member

    Joined:
    Aug 8, 2006
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0
    I have an application that reads some text from file and store data in the array.
    Here is the code :

    Code:
    
    
    TextReader tr = new StreamReader("file.dat");

    CBook tmpBook;
    int i = 0;

    while (tr.Read() > 0)
    {
    tmpBook = new CBook();

    tmpBook.Title = tr.ReadLine();
    tmpBook.Autor = tr.ReadLine();
    tmpBook.Rbr = Convert.ToInt32(tr.ReadLine());
    ....
    }
    tr.Close();
    Code:
    
    

    Problem is that Read() fuction takes the first char of line Title an when i ned to display the Title i have it without first letter.
     
  2. SaswatPadhi

    SaswatPadhi ~ Б0ЯИ Τ0 С0δЭ ~

    Joined:
    May 5, 2009
    Messages:
    1,342
    Likes Received:
    55
    Trophy Points:
    0
    Occupation:
    STUDENT !
    Location:
    Orissa, INDIA
    Home Page:
    http://www.crackingforfun.blogspot.com
    When you use the TextReader's Read function, the next character is read from the file and shifts the position of the Read-Pointer forward.
    So, when you ReadLine after that, all chars except the first appear in the Title.

    You should use Peek instead of Read to check the next character without moving the Read-Pointer. :)

    Code:
    TextReader tr = new StreamReader("file.dat");
    
    CBook tmpBook;
    int i = 0;
    
    while (tr.Peek() > 0)
    {
    tmpBook = new CBook();
    
    tmpBook.Title = tr.ReadLine();
    tmpBook.Autor = tr.ReadLine();
    tmpBook.Rbr = Convert.ToInt32(tr.ReadLine());
    ....
    }
    tr.Close();
    
     
  3. vlado_036

    vlado_036 New Member

    Joined:
    Aug 8, 2006
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0
    Thanks, it work excelent.
     
  4. SaswatPadhi

    SaswatPadhi ~ Б0ЯИ Τ0 С0δЭ ~

    Joined:
    May 5, 2009
    Messages:
    1,342
    Likes Received:
    55
    Trophy Points:
    0
    Occupation:
    STUDENT !
    Location:
    Orissa, INDIA
    Home Page:
    http://www.crackingforfun.blogspot.com

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice