So i met this problem. When i write an ofstream in more than 1 function, my results file "DD.txt" only shows the last ofstream that program did , which is "6". Is there a possible way to do something that my results file have both, 12 and 6 written in it? Thank you!
Calling the std::ofstream constructor by passing a path without passing any flags calls std::ofstream::open() passing the default flags. std::ios::trunc is part of the default flags, which truncates the file if it exists. To append to the file, pass std::ios::app as the second parameter to the constructor.
yes^
Replace ofstream of("DD.txt") with ofstream of("DD.txt", ios::app);
The ios::app will append (add) to the file instead of overwriting. When you do not use a flag like ios::app, it just overwrites the existing data with the new data by default, which is what happened in your case (12 was overwritten by 6).
You might also wanna use of.close() once you are done with the file.
You might also wanna use of.close() once you are done with the file.
In this case that isn't necessary. It is true that the file should be closed when the program has finished using it. However, the ofstream will automatically close the file when it goes out of scope. That is to say, the file is already being closed properly.