writing to .txt file

i have written the following program to get a solution of algebraic equation using newton raphson method. i would like to print the iteration results to a text file "out.txt".after running the program i get the correct answer and "out.txt" gets created,but nothing is written to it. can someone please tell me where there might be an error?

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

main()
{
int i,N=20;
float dx,x=-12.0,y,eph=1.0e-6;
ofstream writer("out.txt");
for(i=1;i<=N;i++)
{
y=x*x+4.0*x+2.0;
if (fabs(y)< eph)
{
cout << "solution to given function is " << x;
exit(1);
}
if(i==N)
{
break;
}
dx=-y/(2.0*x+4.0);
x=x+dx;
writer << x << "\t" << y << "\n";
}
cout << "the solution process has not converged";
writer.close();
return 0;
}
Are you sure?
I ran the above and this is the contents of out.txt:
-7.1	98
-4.74608	24.01
-3.7372	5.54095
-3.44424	1.01785
-3.41453	0.0858239
-3.41421	0.00088309


But you could try this, to close the file properly:
1
2
3
4
5
6
    if (fabs(y)< eph)
    {
        cout << "solution to given function is " << x;
        writer.close();
        exit(1);
    }
Last edited on
hey thank you chervil
after doing the change that you have mentioned, it worked.
i am using code::blocks to compile and run my programs,and I've run the 1st version many a times without any result..and I have used goto statement instead of exit(1); and that move has delivered the output file.

anyway thanks for your timely help
Topic archived. No new replies allowed.