George
George

Reputation: 27

Outputting variables to text file

I have created a file that runs Eulers method and I don't know how to get the variables calculated to appear in a text file. I want every iteration of y and x to be shown. I am sorry but I am very inexperienced with c++ and cant see why this won't work. If someone can help it will be most appreciated.

#include<iostream>
#include <math.h>
#include<fstream>
using namespace std;
int main()
{
    double h = (1.0 / 100.0);
    double y = 0;
    double x = 0;


    for (x = 0; x <= 1; x = x + h)
    {
        y = y + h*(x*exp(3 * x) - 2 * y);


        ofstream demoFile;
        demoFile.open("texttexttext.txt");
        if (!demoFile) return 1;
        demoFile << y << ' ' << x << endl;


    }


    demoFile.close();

    return 0;

}

Upvotes: 0

Views: 121

Answers (2)

NathanOliver
NathanOliver

Reputation: 180660

The problem you are having is you are opening the file every iteration which is causing you to overwrite the file every iteration. If you move the file opening out of the for loop you will get the correct text file.

#include<iostream>
#include <math.h>
#include<fstream>
using namespace std;
int main()
{
    double h = (1.0 / 100.0);
    double y = 0;
    double x = 0;
    ofstream demoFile("texttexttext.txt"); // no need to call open just open with the constructor
    if (!demoFile) return 1;

    for (x = 0; x <= 1; x = x + h)
    {
        y = y + h*(x*exp(3 * x) - 2 * y);

        demoFile << y << ' ' << x << endl;
    }

    return 0;
}

Upvotes: 4

Shahriar
Shahriar

Reputation: 13804

keep these lines outside of your loop.

ofstream demoFile;
demoFile.open("texttexttext.txt");
if (!demoFile) return 1;

Upvotes: 4

Related Questions