How to pass a dat file to a function?

I'm doing excercises to do with functions for college and one of the questions is

A function MaxScore that may be passed the name of a file that contains a set of positive
integer scores and will return the largest score in the file.

I tried to send the file down to the function and loop through the elements of the file to find the largest.

The problem is im not sure how to actually pass the file down to the function so I can work with the elemements inside it.

I know this is totally wrong but I'm only trying to give an idea of what I'm trying to do. This is my first time using a file in a function, I would appreciate if I could be told what I'm doing wrong.

This is what I have so far.

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

using namespace std;
int MaxScore(ifstream& infile, int size);
int main()
{
int array[12];

ifstream infile("array.dat");	//Opens file "Array.dat" for array Initialization.
	ofstream outputFile("output.dat");	//Opens file "output.dat" file for array value storage.


	for (int i = 0; i < 12; i++)
		infile >> array[i]; //Populates elements "array" with data from "Array.dat" file.

	MaxScore(infile, 12);
     
cout << " The largest number in the file = " << MaxScore(infile, 12);
}



int MaxScore(ifstream& infile, int size)
{
	int number = infile[0];
	for (int i = 0; i < 12; i++)
	{
		if (infile[i] > number)
			number = infile[i];	// Gets largest number in the file.
	}

	return number;


}

1
2
3
4
5
6
7
8
9
10
11
int MaxScore(string fileName)
{
   // Your code here
}

int main()
{
string file="array.dat";
cout << " The largest number in the file = " << MaxScore(file) << endl;
return 0;
}
Last edited on
You could use this to partially solve your problem.

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

using namespace std;

int maxScore(std::ifstream& inFile, unsigned int size)
{
	int score;
	int max = std::numeric_limits<int>::min(); // Minimum integer value

	while(inFile >> score && size)
	{
		if(score > max) max = score; size--;
	}

	// Reset ifstream pointer for future use
	inFile.clear(); 
	inFile.seekg(0, inFile.beg);

	return max;
}

int main()
{
	std::ifstream infile("array.dat");	//Opens file "Array.dat" for array Initialization.
	std::ofstream outputFile("output.dat");	//Opens file "output.dat" file for array value storage.
     
	std::cout << "The largest number in the file = " << maxScore(infile, 12) << std::endl;

	return 0;
}
Topic archived. No new replies allowed.