Computer Science Canada Understanding fstream |
Author: | FeZbOy [ Tue Apr 05, 2011 4:24 pm ] |
Post subject: | Understanding fstream |
I am currently in an introduction to C++ course in college. Currently, they are having us use fstream to read from and write to files. (simple .txt files, nothing major) My current problem is this. The program reads from a file of names, pay rates, and hours worked. I have a while loop detecting when the stream fails. When it does, the program finishes. However, the last records are duplicated, as if the stream re-reads the last line. Is there a way to prevent this from happening? Thanks for helping. |
Author: | apython1992 [ Tue Apr 05, 2011 4:51 pm ] |
Post subject: | RE:Understanding fstream |
Can you paste your fstream code? |
Author: | unoho [ Tue Apr 05, 2011 5:01 pm ] | ||
Post subject: | RE:Understanding fstream | ||
i usually do this:
that usually prevents any duplication for last line. |
Author: | FeZbOy [ Tue Apr 05, 2011 5:04 pm ] | ||||
Post subject: | Re: Understanding fstream | ||||
Here is the code.
Also, the hours.txt file
The Gary Phillips line is the duplicated one. |
Author: | apython1992 [ Tue Apr 05, 2011 5:32 pm ] |
Post subject: | RE:Understanding fstream |
According to official C++ documentation: Quote: The function returns true if either the failbit or the badbit is set. At least one of these flags is set when some error other than reaching the End-Of-File occurs during an input operation.
In other words, ios::fail() will not raise any flag at the end of file. I believe what you want is something more like while(file.good()): http://www.cplusplus.com/reference/iostream/ios/good/ |
Author: | FeZbOy [ Tue Apr 05, 2011 5:40 pm ] |
Post subject: | Re: Understanding fstream |
I found the problem. The supplied file had an extra line before the EOF. Clearing that solved the problem. Thanks everyone for all your help! |