The previous answer is correct and useful.
However I just wanted to point out that your code does not match the instructions from your professor. Quote:
My professor also said that it would be a good practice to read from a file like this:
-Read the first thing in the file
-While the end of file flag is not set
+Process what was read
+Read the next thing from the file |
In that scenario, the first item is read from the file before the start of the loop. Inside the loop, the item is processed, and the last thing which is done before the end of the loop is to read the next item.
Although that structure is
almost correct, there is still an error. That is, when the last item is read from the file, the eof() flag may or may not be set, depending on whether there is any trailing whitespace or newline.
Thus, your professor's version with the errors corrected might look something like this. Notice it does
not test for eof() for the reasons mentioned above.
1 2 3 4 5 6 7 8 9
|
fin >> t; // Priming read
while (fin) // check stream is not failed
{
if (IsPrime(t))
fout << t << endl;
fin >> t; // Read the next item
}
|
though I also agree with the version posted above by
shadow fiend as the code is slightly simpler, since it reads the file in only one place instead of two.