c++fstreamofstreamfile-writing

Writing Integers to a .txt file in c++


I am new to C++ and want to write data(integers) on a .txt file. The data is in three or more columns that can be read later for further usage. I have created successfully a reading project but for the writing one the file is created but it is blank. I have tried code samples from multiple sites but is not helping. I have to write results from three different equations as can be seen from the code.

#include<iostream>
#include<fstream>
using namespace std;

int main ()
{
    int i, x, y;
    ofstream myfile;
    myfile.open ("example1.txt");
    for (int j; j < 3; j++)
    {
        myfile << i ;
        myfile << " " << x;
        myfile << " " << y << endl;
        i++;
        x = x + 2;
        y = x + 1;
    }
    myfile.close();
    return 0;
}

Kindly point out the error or suggest a solution.


Solution

  • std::ofstream ofile;
    ofile.open("example.txt", std::ios::app); //app is append which means it will put the text at the end
    
    int i{ 0 };
    int x{ 0 };
    int y{ 0 };
    
    for (int j{ 0 }; j < 3; ++j)
       {
         ofile << i << " " << x << " " << y << std::endl;
         i++;
         x += 2; //Shorter this way
         y = x + 1;
       }
    ofile.close()
    

    Try this: it will write the integers how you want them, i tested it myself.

    Basically what I changed is firstly, I initialized all the variables to 0 so you get the right results and with the ofstream, I just set it to std::ios::app, which stands for appending (it basically will write the integers at the end of the file always. I also just made the writing into one line only.