Need help with Read() function

vlado_036's Avatar, Join Date: Aug 2006
Go4Expert Member
I have an application that reads some text from file and store data in the array.
Here is the 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();

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.
SaswatPadhi's Avatar, Join Date: May 2009
~ Б0ЯИ Τ0 С0δЭ ~
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: C#
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();
vlado_036 like this
vlado_036's Avatar, Join Date: Aug 2006
Go4Expert Member
Thanks, it work excelent.
SaswatPadhi's Avatar, Join Date: May 2009
~ Б0ЯИ Τ0 С0δЭ ~
My pleasure