Output Stream Issue

I have run into an issue while experimenting with input and output files. When writing output to a file using a loop, the file seems to be empty (file size is 0 bytes) when there is no end line statement inside the loop. The file contains data when the end line statement is inside the loop.

This results in an empty output file.
1
2
3
for (i = 0; i < name.size(); i++) {
   ost << name[i] <<"\n";
}



This results in a proper output file..
1
2
3
for (i = 0; i < name.size(); i++) {
   ost << name[i] << endl;
}


This also results in a proper output file.
1
2
3
4
for (i = 0; i < name.size(); i++) {
   ost << name[i] <<" ";
}
ost << endl;



Why is this? I understand that the end line statement flushes the output stream. Is flushing necessary for the output stream to deposit data to the output file and close it?
Last edited on
Yes flushing is necessary for the output stream to deposit data to the file. However, when you explicitly close the output stream object or if the stream object goes out of scope, the data will be automatically flushed to the file.
Thanks for the explanation. Little by little my understanding of C++ is improving.
Topic archived. No new replies allowed.