Calling a stream in a function

So I am writing a very simple program that prompts a user to input a file name. Assuming file name enters exists, the program will display the largest and smallest numbers to the screen. When I run the program, the largest output is correct, but the smallest displays a number not even in the file. If I switch the order of the largest and smallest function calls, the smallest displays correctly, but the largest does not. Any help would be greatly appreciated.

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
67
68
69
70
71
72
73
74
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <climits>

using namespace std;

void largest(ifstream& numbers, int& max);
void smallest(ifstream& numbers, int& min);
void output(int max, int min);

int main()
{

	int max = -INT_MAX, min = INT_MAX;

	char file_name[16];
	cout << "Enter the file_name ";
	cin >> file_name;
	ifstream numbers;
	numbers.open(file_name);
	if (numbers.fail( ) )
	{    
		cout << "Input file opening failed." << endl;
		exit(1);
	}

	largest(numbers, max);
	smallest(numbers, min);
	output(max, min);

	return 0;
}

void largest(ifstream& numbers, int& max)
{
	int next;

	while (numbers >> next)
	{
		if (next > max)
			max = next;
	}

	numbers.close();
}

void smallest(ifstream& numbers, int& min)
{
	int next;

	while (numbers >> next)
	{
		if (next < min)
			min = next;
	}

	numbers.close();
}

void output(int max, int min)
{
	char exit;

	cout << "The largest number is "
		 << max
		 << endl
		 << "The smallest number is "
		 << min
		 << endl
		 << endl
		 << "Enter any character to exit: ";
	cin >> exit;
}
I got it to work.

I just opened the file again between the largest and smallest functions like this:

1
2
3
4
largest(numbers, max);
numbers.open(file_name);
smallest(numbers, min);
output(max, min);


Is this the best way to go about this, or is there a better way? FYI, I am still very much a noob at programming.
Last edited on
If you close the file at the end of largest() this is the only way to go
Topic archived. No new replies allowed.