please help me look at this code..the results is not what I expect..

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!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#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;
}
 
std::ios::trunc


it means the file will be truncated (i.e: all content will be erased)
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.
Last edited on
Topic archived. No new replies allowed.