hw7 code #include<iostream> #include<fstream> #include<climits> #include <string
ID: 3554983 • Letter: H
Question
hw7 code
#include<iostream>
#include<fstream>
#include<climits>
#include <string>
using namespace std;
int processFile(ifstream& ifile, long ithVal, long& retIthVal, long& minimum, long& maximum)
{
long num;
maximum = LONG_MIN;
minimum = LONG_MAX;
int i = 0;
while(ifile>>num)
{
if(num>maximum)
maximum = num;
if(num<minimum)
minimum = num;
i++;
if(i==ithVal)
retIthVal = num;
}
if(ithVal < i)
return 0;
else
return 1;
}
int main()
{
string fname,line;
long i, ithVal, min, max;
cout<<"Input File Name: ";
cin >> fname;
ifstream myfile;
myfile.open(fname.c_str());
if (myfile)
{
cout<<"Unable to open "<<fname<<endl;
}
cout<<"Which number do you want to return? ";
cin>>i;
int ret = processFile(myfile, i, ithVal, min, max);
cout<<"Min is {"<<min<<"}. ";
cout<<"Max is {"<<max<<"}. ";
if(ret==0)
cout<<" Value{"<<i<<"} is "<<ithVal<<". ";
else
cout<<" There aren't that many numbers in the file! ";
myfile.close();
return 0;
}
Explanation / Answer
#include<iostream>
#include<fstream>
#include<algorithm>
#include<climits>
#include <string>
using namespace std;
int readArray(ifstream& ifile,long arr[])
{
long num;
int i = 0;
while(ifile>>num)
{
arr[i]=num;
i++;
if(i==1000)
break;
}
return i;
}
void sortArray(long arr[],int numberInTheArray)
{
sort(arr,arr+numberInTheArray);
}
int main()
{
string fname,line;
long i, ithVal, min, max;
long arr[5000];
cout<<"Input File Name: ";
cin >> fname;
ifstream myfile;
myfile.open(fname.c_str());
if (!myfile)
{
cout<<"Unable to open "<<fname<<endl;
return 0;
}
cout<<"Which number do you want to return? ";
cin>>i;
int ret = readArray(myfile,arr);
cout<<ret<<endl;
max = LONG_MIN;
min = LONG_MAX;
for(int j=0;j<ret;j++)
{
if(max<arr[j])
{
max=arr[j];
}
if(min>arr[j])
{
min=arr[j];
}
}
ithVal=arr[i-1];
cout<<"Before sort: "<<endl ;
cout<<"Min is {"<<min<<"}. ";
cout<<"Max is {"<<max<<"}. ";
if(ret!=1000)
cout<<"Warning: Only "<<ret<<" numbers were read into the array"<<endl;
if(i>1000)
{
cout<<i<<" is bigger than 1000!"<<endl;
}
else if(i<=ret)
cout<<"Value{"<<i<<"} is "<<ithVal<<". ";
else
cout<<"There aren't that many numbers in the file! ";
sortArray(arr,ret);
cout<<" After Sort"<<endl;
cout<<"Min is {"<<min<<"}. ";
cout<<"Max is {"<<max<<"}. ";
if(ret!=1000)
cout<<"Warning: Only "<<ret<<" numbers were read into the array"<<endl;
if(i>1000)
{
cout<<i<<" is bigger than 1000!"<<endl;
}
else if(i<=ret)
cout<<"Value{"<<i<<"} is "<<arr[i-1]<<". ";
else
cout<<"There aren't that many numbers in the file! ";
myfile.close();
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.