I suspect the fstream has gone into a failed state after the first read because you read through the entire file and encountered EOF which triggered the fail bit. Try placing this line:
File.clear();
after the while loop is done, (so you've stopped the loop because you got to the end of the file) and before this line:
File.seekg(0, ios::beg);
Also, it's not a good idea to use the return of eof() as the stop condition of a loop because it can corrupt your data.
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
> what do u suggest to use as stop condition instead of
the return of eof()
Say the file consists of nine ints.
Rather than this:
while(!fin.eof())
{
fin >> num;
}
I would suggest this:
while(fin >> num)
{}
Using the return of eof() as the return value is prone to introducing error because of the technicalities associated with how eof() works. Basically, it often allows the loop to run one to many times.
Using a stream method that reads in data as the conditional will allow the loop to fail gracefully, and without "overreading the file", whatever causes the input to fail. Finding EOF is one of the conditions that would put the stream in a failed state and terminate the input, but there are other, more nefarious things that could happen as well.
As to why if(file) doesn't work all the time but if(!file) does, I don't know. Sorry. You could try if(file.good()) instead of if(file) if you want to accentuate the positive instead of the negative, I suppose.
Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396