File IO

i have this problem, i need to display the maximum, the minimum and the average of this data and display the results in another text file.

1 1000.25
2 55.25
3 9999.99
4 33.45
5 2000.00
6 1588.88
7 1699.99
8 14898.25
9 13734.21
10 13523.24

this is my data file.

here is my code if anyone can help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>

using namespace std;

void openInput(ifstream&);
void openOutput(ofstream&);
double fileData(ifstream&, ofstream&);

int main()
{
   ifstream inFile;
   ofstream outFile;

   openInput(inFile);
   openOutput(outFile);
}

void openInput(ifstream& fname){

   string filename = "prices.dat";                         
   int id;
   int numItems;
   double price;
                                     

   fname.open(filename.c_str());                            
   
   if ( !fname ) 
   { 
      cout << "File-open failure\n";   
      exit(1); 
   }

   fname >> numItems;                                     
   cout.precision(2); 
   cout.setf( ios::fixed );   

   while( fname >> id >> price )                         
   {
      //count++;

      cout << setw( 3 ) << id << " " << setw(10) << price <<endl;  
   }
   return;
}

void openOutput(ofstream& outFile){

      outFile.open("output.dat");

      outFile.close();

   return;
}

double fileData(ifstream& inFile, ofstream& outFile){

   double average;
   
   return 0;

}
Last edited on
What does it do that you don't like, or what does it not do that you wish it did do?
You should probably work on your function names. You have a function called openInput which not only opens but also reads the input. This input is read into local variables and written to stdout. These values are not available to the rest of the program as soon as the function returns.

You have another function named openOutput which opens and then immediately closes an output file.

Your third function fileData appears to be the function that will do the work that needs to be done. In needs an input file to read data from and an output file to write data to.

I recommend that openInput should only open the input file and openOutput should only open the output file (nothing else except except error checking that the file opened). These open files are returned by reference to main(). At that point you can pass the open files to fileData which reads the input, processes it, and writes the output to the output file.

Before leaving main you should close the input and output files, but you don't need separate functions for that--simply call openInput.close();
Topic archived. No new replies allowed.