Find Maxima from Text File

Hello everyone, my objective is to find the maximum number from a text file containing 1000 numbers, however I have not been able to do so. Any help would be appreciated. I am referring to case 2 in my code.(Also I am familiar with only the iostream and fstream libs.)
Thanks



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
75
76
77
78
79
80
81
82
83
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

int main()
{
	string line;
	int userChoice;
	bool isRightinput = false;
	float mean;
	char again,y,n;
	int counter = 0, total = 0, number = 0;
	int val = 0, maxVal = 0, counter2=0;
	ifstream myfile ("numbers.txt");
	while(isRightinput == false)
		{
			cout<<"Main Menu"<<endl<<"Please enter the number for one of these options: "<<endl<<
			"1 - Mean"<<endl<<"2 - Maxima"<<endl<<"3 - Minima"<<endl<<"4 - Search"<<endl<<"Your Choice: ";
			cin>>userChoice;
			switch (userChoice)
				{
					case 1:
					if (myfile.is_open())
						{
							while (myfile.good())
								{
									myfile>>number;
									counter++;
									total = total  + number;
								}
						}
					mean = total/counter;				
					cout<<"The mean of the data set is "<<mean<<endl;
					cout<<"Would you like to choose another number? [y,n] ";
					cin>>again;
					if (again == y)
						{
							isRightinput = false;
						}
					else
						{
							isRightinput = true;
						}
					break;				
					case 2:
					if(myfile.is_open())
						{
							while(myfile.good())
								{
									myfile>>val;
									
									if(val>maxVal)
										{
											val=maxVal;
											counter2++;
										}
										
										
								}
						}			
					
					cout<<"The maximum number is "<<maxVal<<endl<<val;
					isRightinput = true;
					break;
					case 3:
					cout<<"min";
					isRightinput = true;
					break;
					case 4:
					cout<<"ser";
					isRightinput = true;
					break;
					default:
					cout<<"Please enter a valid number"<<endl;
					
				}
		
	}

	return 0;
}
Last edited on

if(val>maxVal)
{
val=maxVal;
counter2++;
}


Well here you go!!!
val > maxVal, so the number from the file is larger, but then instead of setting the maxVal to the new number, you set the val to the maxVal,

Right would be: val=maxVal should become: maxVal = val;
John2,
Thank you for pointing out this small but 6 hour long problem. I hope you have a great day!
Topic archived. No new replies allowed.