Search code examples
c++storing-data

Storing data in a file (C++)


I am fairly new to C++ and I am currently trying to save some of the data that my program produces in a file. My code outputs values for two variables, A and B. Considering I am aiming to plot A vs B, what is the best way of approaching this? I was thinking of creating an array, but perhaps creating a .txt file with two columns will be easier.

I have tried looking into it and it appears that this is easier said than done. I don't know much about pointers, but I suspect I may need to know more before attempting this.

Here is my code:

#include <iostream>
using namespace std;

int main()
{
    for (int a = 10, b = 5; 0 < a < 20 && b < 50;)
    {
        int B = b + a;
        cout << "B = " << B << endl;
        int A = a - b;
        cout << "A = " << A << endl;
        b = B;
        a = A;
    }
}

This outputs:

B = 15
A = 5
B = 20
A = -10
B = 10
A = -30
B = -20
A = -40
B = -60
A = -20
B = -80
A = 40
B = -40
A = 120
B = 80
A = 160

Any hints? Thanks.


Solution

  • If you want to store data in a file, here's how you'd go about doing that:

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
        ofstream fout("filename.txt");
        for (int a = 10, b = 5; 0 < a && a < 20 && b < 50;)
        {
            int B = b + a;
            int A = a - b;
            fout << B << " " << A << endl;
            b = B;
            a = A;
        }
        fout.close();
    }