I am a beginner who is practicing with the ofstream. I wrote a code as follows. I was expecting when I enter number 0, I can get "I am here." but only " hello world!" is got when enter 0..so I don't understand the function of "std::ios::trunc". it doesn't mean: when I enter 0, the sentence "Hello world" is replaced by "I am here."? I am a beginner..please help me look at it..Thanks very much!!
#include <cstdlib>
#include <iostream>
#include <fstream>
int main(int argc, char** argv) {
std::ofstream myfile;
myfile.open ("example.txt");//creat a file called example.txt
myfile<<"Hello world!"<<std::endl;
int Num;
std::cout<<"please enter a number:";
std::cin>> Num;
if (Num!=0)
{
myfile<<"this world is beautiful and I am fabulous."<< std::endl;
myfile.close();
}
else
{
myfile.open("example.txt", std::ios::trunc);
myfile<< "I am here."<<std::endl;
myfile.close();
}
return 0;
}
You don't ever close myfile after opening it at line 7. So when you try to open it again at line 20, I assume it's failing to open the file, as it's already open. This might then cause later behaviour to be unpredictable.
Try closing the file, before re-opening it in a different mode.