-
RoD, I would say that her "fix" is the least good of the ones I've seen here. It most certainly ain't the standard way of doing it. The cleanest, most standard and best way do do it would be (as others have already pointed out) while(infile >> data) {...}or while(!infile.eof()) { infile >> data; ...}. In other words, don't listen to her.
-
>>In other words, don't listen to her.
>>while(!infile.eof()) { infile >> data; ...}
I'm afraid your advice isn't much better. Controlling the loop with !eof is not the way to do things, as already highlighted.
-
>>In other words, don't listen to her.
Out of the question. She is a teacher of a field i am trying to learn, anything she says has at least a certain degree of benifit or validitity that it carries with it.
-
I went into every one of my CS classes having already learned the subject matter. What ever else you pick up from the class is a bonus.
gg
-
Hammer, about infile.eof(); I didn't notice that the file was ended with endl. If there hadn't been a newline charater at the end of the file eof() would work. Sorry about that, should have read the code more careful. However, eof() should be prefered over using fail() in a case like this (even if it, like you said, won't work in this particular case), don't you agree? It seems kind of dumb to wait for something to fail before you terminate it.
RoD, I didn't suggest you should never listen to her (even though she deserves it after kicking you out of the class room), just not in this case since she is obviously wrong.
-
IMO, any code that reads the last line of a file twice is wrong. Whether you use fail() or eof() or != flag, seems immaterial.
As Hammer points out in his side post, using C code, but that's okay, fail() and eof() don't check the stream/streambuf directly, they check the state variable of the stream. In this case when the ifstream finds EOF it flips the EOF bit of the state variable; but finding EOF doesn't cause an istream to fail, therefore the fail bit isn't flipped. Therefore the loop continues for one last cycle, although in an undetermined way--often by repeating the last item read in, but you can't count on that.
IMO, another reason the initial approach is wrong is that if the program continues beyond this snippet and you attempt to use the ifstream again, say to read in from another file, without clearing the fail bit using clear(), then the stream will contiue to fail indefinately.