Search code examples
c++fstreamfile-handlingofstream

How to use fstream, to write different values in a .txt file


The problem I am facing is the following: if we define something like

ofstream myFile; 

    myFile.open("Directory//debug.txt");
    for (int i = 0; i < 10; i++)
    {
     myFile << i << endl;
     myFile.close(); 
    }

the output in the debug file will be 9. I want to make it so that it outputs all the numbers from 0 to 9. Aside from closing the file after the for statement is it possible to define an ofstream that would do that?


Solution

  • No. You have two options:

    Close the file outside the loop:

    myFile.open("Directory//debug.txt");
    for (int i = 0; i < 10; i++)
    {
        myFile << i << endl;
    }
    myFile.close();
    

    or open the file in append mode and close inside the loop:

    for (int i = 0; i < 10; i++)
    {
        myFile.open("Directory//debug.txt", ios_base::app);
        myFile << i << endl;
        myFile.close(); 
    }