How to take info from a text file and put it into a function and take the output and put it into a new file

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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

  float rowAverage(float val1, float val2, float val3, float val4, float val5) 
{
  float sum = val1 + val2 + val3 + val4 + val5;
  float average = sum / 5.0;
  return average;
}

int main() 
{
  ifstream input("inputData.txt");
  ofstream output("averages.txt");
  
  float average, val1, val2, val3, val4, val5;
  //string fname, lname;
  
  //getline(fname, lname);
  
  while(!input.eof())
  {
  	
  	input >> val1 >> val2 >> val3 >> val4 >> val5;
  	rowAverage(val1, val2, val3, val4, val5);
  	output << rowAverage;
  	
  	
    
  }
  
    output.close();
	input.close();
	cout << "done";
	return 0;
}

Last edited on
Lines 28-29 should read
1
2
  	average = rowAverage(val1, val2, val3, val4, val5);
  	output << average << '\n';


Or simply
output << rowAverage(val1, val2, val3, val4, val5) << '\n';

You could get away with
1
2
3
4
5
6
7
8
9
10
#include <fstream>

int main() 
{
  std::ifstream input{"inputData.txt"};
  std::ofstream output{"averages.txt"};

  for (float a, b, c, d, e; input >> a >> b >> c >> d >> e; ) 
    output << ((a + b + c + d + e) / 5.0f) << '\n';
}
Last edited on
I wish I was allowed to do that, but he wanted the function but didn't tell us the parameters of how to write outputting information from a function to a file so thank you so much.
Last edited on
Your read loop has an issue as eof() doesn't work the way you're thinking it is. eof() is only set once you try to read past eof - not when a read is successful but the read ends at end-of-file. It's normal to put the file extraction in the while loop. Also, there's no check that the input file has been opened OK.

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
#include <iostream>
#include <fstream>

using namespace std;

float rowAverage(float val1, float val2, float val3, float val4, float val5)
{
	return (val1 + val2 + val3 + val4 + val5) / 5.0;
}

int main()
{
	ifstream input("inputData.txt");

	if (!input.is_open())
		cout << "Cannot open input file\n";
	else {
		ofstream output("averages.txt");

		float average, val1, val2, val3, val4, val5;

		while (input >> val1 >> val2 >> val3 >> val4 >> val5)
			output << rowAverage(val1, val2, val3, val4, val5) << '\n';

		output.close();
		input.close();
	}

	cout << "done";
	return 0;
}

Topic archived. No new replies allowed.