Interestingly, though, I didn't have to close it, which is very odd. Why is it always recommended that you close text files? I'm hoping I don't run into a huge issue in the future. |
The difference in my code was that I just used '\n' to output a newline character at the end of each line. In your code you used endl. The difference is that endl first sends the '\n' and then flushes the buffer, that is, it forces it to be physically sent to the hard drive. Mostly we don't want to do this with disk files, it can lead to lots of unnecessary disk activity. Instead we let the system automatically send the contents of the buffer to the disk whenever it is full, and when the file is closed.
Closing the file also frees up the resources and makes them available for use elsewhere. In the case of abnormal program termination, files which are not properly closed may lead to data loss.
I also am not quite sure where "applee" came from, but I'm still very, very new to this. I wouldn't want to take up more of your time if you're busy. |
To understand this you need to grasp two things:
• how a loop works
• when is the eof() flag set
So, considering this piece of code:
1 2 3 4 5 6 7
|
istringstream reader("apple");
while (!reader.eof())
{
reader.get(letter);
cout << letter;
}
|
At the start, the first time we get to line 3, it is not end of file so the body of the loop is entered. At line 5 a character is read and displayed at line 6.
Then control goes back to the top of the loop. The condition is tested: is it eof? No, so the process repeats for each letter.
When we get to line 5 and get the last letter, everything is still ok, the character is read successfully, it hasn't yet hit the end of file. So the letter 'e' is output and control goes back to line 3. Is it eof? No. So the body of the loop is entered one more time. At line 5, the get() will fail, and the eof flag is set. We proceed to line 6, output the existing character stored in letter. That's another 'e'. Next, we go back to the start of the loop, test eof(), find it is true, and quit the loop.
Hope that makes some kind of sense, sometimes fairly simply ideas can seem complicated when written down. Anyway, time spent learning the basics is well spent, it can save hours of pain later.
Note, we could fix the code like this:
1 2 3 4 5 6 7 8
|
istringstream reader("apple");
reader.get(letter);
while (!reader.eof())
{
cout << letter;
reader.get(letter);
}
|
...but that means the get() has to be done in two different places.
It's better to just put the get() (or other input operation) inside the loop condition as I did with the 'orange' example.