Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/forums/c-sharp/)
-   -   Need help with Read() function (http://www.go4expert.com/forums/help-read-function-t19876/)

vlado_036 24Oct2009 16:25

Need help with Read() function
 
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 25Oct2009 08:41

Re: Need help with Read() function
 
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 25Oct2009 13:46

Re: Need help with Read() function
 
Thanks, it work excelent.

SaswatPadhi 25Oct2009 18:58

Re: Need help with Read() function
 
My pleasure :)


All times are GMT +5.5. The time now is 05:04.