LinuxQuestions.org
View the Most Wanted LQ Wiki articles.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Search this Thread
Old 02-07-2006, 05:08 PM   #1
Nylex
LQ Addict
 
Registered: Jul 2003
Location: London, UK
Distribution: Slackware
Posts: 7,464

Rep: Reputation: Disabled
C++ - problem with writing to files


Hi people, I have written a program that does some calculations (if you care, it approximates a definite integral using both Simpson's rule and the trapezium rule for different numbers of sub-intervals, along with relative errors) and is supposed to output the results to both the screen and to a file. It outputs the results to the screen fine, but it seems to only write the last set of results to the file:

Code:
nick@nick:~/Uni/CompPhys$ ./ws3-ex1
log n           log epsilon_t           log epsilon_s
1               -2.53607                -4.60311
1.30103         -3.13741                -5.79587
1.47712         -3.48946                -6.49806
1.60206         -3.73929                -6.99705
1.69897         -3.93309                -7.38433
1.77815         -4.09144                -7.70087
1.8451          -4.22533                -7.96854
1.90309         -4.34131                -8.20043
1.95424         -4.44361                -8.40499
2               -4.53512                -8.58798
2.04139         -4.61791                -8.75352
2.07918         -4.69348                -8.90465
2.11394         -4.76301                -9.04369
2.14613         -4.82737                -9.17241
2.17609         -4.8873         -9.29225
2.20412         -4.94336                -9.40436
2.23045         -4.99601                -9.50967
2.25527         -5.04566                -9.60896
2.27875         -5.09262                -9.70288
2.30103         -5.13718                -9.79198
Code:
nick@nick:~/Uni/CompPhys$ cat ws3-ex1-data1 
2.30103         -5.13718                -9.79198
My code:

Code:
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;

double f(double x);
double trapezium(double (*pFunc)(double x), double upper, double lower, int n);
double simpson(double (*pFunc)(double x), double upper, double lower, int n); 

int main()
{
  double exact = 0.5;
  const int maxIntervals = 200;
  ofstream out("ws3-ex1-data");

  cout << "log n\t\t" << "log epsilon_t\t\t" << "log epsilon_s" << endl; // table header row

  for(int n = 10; n <= maxIntervals; n += 10)
  {
 
    double trResult = trapezium(f, 1, 0, n);
    double trError = fabs((trResult - exact) / exact);
    double srResult = simpson(f, 1, 0, n);
    double srError = fabs((srResult - exact) / exact);
    cout << log10(double(n)) << "\t\t" << log10(trError) << "\t\t" << log10(srError) << endl;
    out << log10(double(n)) << "\t\t" << log10(trError) << "\t\t" << log10(srError) << endl;
  }

  return 0;

}

double f(double x)
{
  return 1.0 / pow((1.0 + x), 2);
}

double trapezium(double (*pFunc)(double x), double upper, double lower, int n)
{
  double width = upper - lower;
  double tW = width / double(n); 
  double fLower = pFunc(lower);
  double fUpper = pFunc(upper);
  double result = (0.5 * (fLower + fUpper)) * tW;

  for(int i = 1; i < n; i++)
    result += tW * pFunc(lower + (tW * i));

  return result;
}

double simpson(double (*pFunc)(double x), double upper, double lower, int n)
{
  double h = (upper - lower) / n;
  double result = (h / 3) * (pFunc(lower) + pFunc(upper));

  for(int j = 1; j < (n / 2); j++)
  {
    int i = 2 * j;
    double xI = lower + (i * h);
    result += ((2 * h) / 3) * pFunc(xI);
  }

  for(int j = 1; j <= (n / 2); j++)
  {
    int i = (2 * j) - 1;
    double xI = lower + (i * h);
    result += ((4 * h) / 3) * pFunc(xI);
  }

  return result;
}
I can't see why all the values aren't being written to the file :/. All help appreciated!

Last edited by Nylex; 02-07-2006 at 05:15 PM.
 
Old 02-07-2006, 05:19 PM   #2
dmail
Member
 
Registered: Oct 2005
Posts: 970

Rep: Reputation: Disabled
two options
a:
write all the data to a stream, open the file "<<" direct it into the file and flush, close the file.
b:
open the with the ios::app flag to append to the end of the file.

i dont see you closing it, does it close at exit?
have alook at this example
http://www.cplusplus.com/ref/iostrea...ream/open.html

two? im sure theres more options.

Last edited by dmail; 02-07-2006 at 05:25 PM.
 
Old 02-07-2006, 05:28 PM   #3
Nylex
LQ Addict
 
Registered: Jul 2003
Location: London, UK
Distribution: Slackware
Posts: 7,464

Original Poster
Rep: Reputation: Disabled
dmail, thanks for the reply. I assume it closes on exit! I'll try those things.

I'm a bit confused, because another (albeit shorter) program I wrote works:

Code:
  ofstream out("data");                          
  
  cout << "x\t" << "(sin x)e^-x" << endl;           
  for(double x = 0.0; x <= M_PI; x += 0.001)
  {
    double y = exp(-x) * sin(x);                   
    cout << x << "\t" << y << endl;                 
    out << x << "\t" << y << endl;                   
  }
What's the difference between this one and the first one in terms of writing to the file?

Last edited by Nylex; 02-07-2006 at 05:29 PM.
 
Old 02-07-2006, 05:39 PM   #4
dmail
Member
 
Registered: Oct 2005
Posts: 970

Rep: Reputation: Disabled
Im unsure to be honest i normaly collect the data and then direct it to file, or as i suggested append to the file.
You really should close the file tho and its a good idea to flush so that you empty the stream.

it should work theres not any real diffs i can see from a piece of my code.
Code:
void save_to_file()
{
	char file_name[]="memory_leaks.txt";
	out.open( file_name, std::ios::out );

	if(!out.is_open())
		{cout <<"ERROR\ncould not open file " <<file_name <<endl;}
	else 
	{
		for(ptr_iter = ptr_vector.begin(); ptr_iter != ptr_vector.end(); ++ptr_iter)
		{
			out <<"address:" <<ptr_iter->address <<" "
				<<"size:" <<ptr_iter->size 
				<<"\n\tfile:" <<ptr_iter->file <<" "
				<<"\n\tline:" <<ptr_iter->line <<" " <<"\n";
		}
		out <<"\0";
		out.close();
	}
}
where out is an ofstream

Last edited by dmail; 02-07-2006 at 05:46 PM.
 
Old 02-07-2006, 06:00 PM   #5
xhi
Senior Member
 
Registered: Mar 2005
Location: USA::Pennsylvania
Distribution: Slackware
Posts: 1,065

Rep: Reputation: 45
Nylex, the way you are writing to the file should work. Like dmail suggested you could try to flush the buffer..

out.flush()

after every write and see what happens..

i may be mistaken but i think that fstream destructor will close the file and you do not have to explicitly close it unless you would want to reopen a file with that stream var..
 
Old 02-08-2006, 01:13 AM   #6
Nylex
LQ Addict
 
Registered: Jul 2003
Location: London, UK
Distribution: Slackware
Posts: 7,464

Original Poster
Rep: Reputation: Disabled
Thanks both of you, it seems to work now!
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
writing to files in C ocularbob Programming 9 02-17-2004 12:06 PM
writing in read only files endezeichen Linux - Software 3 12-20-2003 03:48 PM
Command for writing over files? soulflyer Linux - Newbie 2 12-12-2003 05:26 PM
Writing Scripts or Batch files? Nicksan Linux - Software 1 06-29-2003 11:49 PM
Writing Single files to a CD jimmmac Linux - Software 11 04-27-2003 04:20 PM


All times are GMT -5. The time now is 07:35 PM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration