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