Originally Posted by DaWei
You have a couple of issues. One not pertaining to the sort is that you did not test the input open or the input read to see if they succeeded. That just a newbie mistake. Now that you know about it, I'm sure you won't make it again. Sure, you can luck out, but you are courting failure.
The sort is working. That is because you are saving the 1 twice. It's a perfect example of why conditioning the while on EOF is not enough. The one is followed by a newline, which terminates the read. It does not generate an EOF because the newline terminated the read; thus you did not hit end of file. You go around the loop one more time. You hit EOF. Because you did not test AFTER the read which resulted in EOF and BEFORE you saved t, you just saved t again, which is the old data, the 1.
Test the read for .good (). If it's not good, it could be either a failure or EOF. In that case, test if for .eof(). If it's EOF, you're done. If it's not .good () and not .eof(), you have a failure. Notify the user and bail.
The problem could be fixed by removing the last newline, but that would be stupid. You can't guarantee what your user's file will be like.
Pay attention to the correct count, as mentioned by Shabbir.
Thanks . I'll make sure next time that I do check if the file has been successfully opens for reading and writing and also successfully closed too . I will read into that on how to do it .
I think I am getting why it is putting an extra time the last input . But havent been able to rectify it.
I tried the following two codes:
But none is fixing that problem.
Should the checks be implemented in some other way ?