minimum and maximum in a file

Hi
I have to find the minimum and maximum number from the input file and output it on another 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<fstream>
#include<cstdlib>
#include<iostream>
using namespace std;

int main()
{
	int counter=0;
	double number, sum=0, average, max, min;
	ifstream read;
	ofstream write;
	
	read.open("numbers.txt");
	if (read.fail())
	{
		cout<< "Input file opening failed.\n";
		exit(1);
	}

	write.open("output.txt");
	if(write.fail())
	{
		cout << "Output file opening failed.\n";
		exit(1);
	}

	while (read>>number)
	{
		counter++;
		sum=sum+number;
	}
    average=sum/counter;

    while (!read.eof())
	{
		max=number;
		if (number>max)
		max=number;
		min=number;
		if (number<min)
		min=number;
	}

	
	write<<"There are "<<counter<<" numbers in the file numbers.dat\n";
	write.setf(ios::fixed);
	write.setf(ios::showpoint);
	write.precision(3);
	write<<"The average of all numbers is "<<average<<endl;
	write<<"The maximum number is "<<max<<endl;
	write<<"The minumum number is "<<min<<endl;
	
	
	read.close();
	write.close();

	return 0;
}

When i run it, it says max and min is being used without being initialized.
Then i put
1
2
3
read>>number;
max=number;
min=number;
after line 25 but then it just kept giving me the first number in the input file in stead of running
1
2
3
4
                 if (number>max)
		max=number;
		if (number<min)
		min=number;
to find the real max and min.
how do I find the max and min?
That second while loop wasn't doing anything because the first while loop will read through the entire file and the way you were setting your max and min values was pretty weird.

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
	int counter=0;
	double number, sum=0, average, max = INT_MIN, min = INT_MAX;
	ifstream read;
	ofstream write;
	
	read.open("numbers.txt");
	if (read.fail())
	{
		cout<< "Input file opening failed.\n";
		exit(1);
	}

	write.open("output.txt");
	if(write.fail())
	{
		cout << "Output file opening failed.\n";
		exit(1);
	}

	while (read>>number)
	{
		if (number>max)
		     max=number;
		
		if (number<min)
		     min=number;
               
                sum=sum+number;
                counter++;
	}
    average=sum/counter;
	
	write<<"There are "<<counter<<" numbers in the file numbers.dat\n";
	write.setf(ios::fixed);
	write.setf(ios::showpoint);
	write.precision(3);
	write<<"The average of all numbers is "<<average<<endl;
	write<<"The maximum number is "<<max<<endl;
	write<<"The minumum number is "<<min<<endl;
	
	
	read.close();
	write.close();
Last edited on
Topic archived. No new replies allowed.