Hey forum! I have looked at numerous threads on here, but could not find any that would fix my problem so I thought I would make my own thread. I want to run a number through an algorithm then have the number and the count of how many times it ran through write out to a file so I can look for patterns. Here is my code
// open the file.
ofstream file("collatz_write.txt", ios::app|ios::out);
for (i=0; i<100; i++) {
// attempt to open the already open file.
file.open("collatz_write.txt"/*, ios::app|ios::out*/);
// file is now in an error state.
If you successfully open a file, any subsequent attempts to open the file without an intervening call to close will fail, putting the file stream into an error state. All subsequent use of the file stream will fail, since the error state is never cleared.
If you open a file for output with the default flags, the file will be truncated.
I would suggest opening the file once before the for loop is entered and using it to write data within the body of the for loop. You can then let the destructor close the file stream when it goes out of scope.