0

How does it work when you use a while loop with the condition !fin.eof()? What if my loop contains a statement like fin.get(ch) where ch is of type char?

  • How exactly does the pointer move and when is it updated?
  • If at the beginning of the file, the pointer points to the 1st element. Does it move over to the second element in the first iteration itself?
  • It depends on what you do in your loop ... – Marged Dec 29 '15 at 01:36
  • 4
    "How does it work"? -- It *doesn't* work. `while (!fin.eof())` is never correct. – Kerrek SB Dec 29 '15 at 01:44
  • 1
    To further @KerrekSB s point http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong – Fantastic Mr Fox Dec 29 '15 at 02:17
  • @KerrekSB well it *could be* correct but it's good to avoid it anyway. – M.M Dec 29 '15 at 02:58
  • @M.M: Hm. I'd say checking the condition `fin.eof()` has its uses (e.g. when combined with `>> std::ws`), but the entire loop `while (!fin.eof())` seems bogus: If you're just discarding the entire stream, then use `ignore`, and otherwise there must be some operation happening in the loop that changes the EOFness of the stream, and that operation needs to be checked for success. – Kerrek SB Dec 29 '15 at 10:26

1 Answers1

0

fin.eof() increments the pointer to the next character in the input buffer. This might include a newline character or other hidden character which comes after what you are expecting. "it reads characters from the current stream position to and including the first newline character, to the end of the stream, or until the number of characters read is equal to n – 1 [for fgets], whichever comes first." (from http://www.cplusplus.com/forum/beginner/37005/)

I've found that

while (getline(fin,sent))

usually works better (see http://mathbits.com/MathBits/CompSci/Files/End.htm)

fierlion
  • 1
  • 1
  • 2
    I think you meant `fin.get(ch)` at the beginning there, not `fin.eof()`; the latter would presumably not increment a thing. – ShadowRanger Dec 29 '15 at 01:56