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 84 85 86
|
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int processFile(ifstream& ifile, long i, long& retIthVal, long& minimum, long& maximum);
int main()
{
long i,
retIthVal,
minimum,
maximum;
int returnvalue=1;
ifstream ifile; //variable for myfile
string strVar; //variable for textfile
cout << "Input File Name: "; //prompts for user file
cin >> strVar; //inputs textfile into string
ifile.open(strVar.c_str());
if (!ifile) // the ! means myInfile is non 0, indicating it is OK
{
cout << "\nThat file does not exist!\n"; //shows this if file is wrong
return 1;
}
cout << "Which number do you want to return? ";
cin >> i;
returnvalue=processFile(ifile, i, retIthVal, minimum, maximum);
if(returnvalue==0)
{
cout << "Min is {" << minimum << "}." << endl;
cout << "Max is {" << maximum << "}.\n" << endl;
cout << "Value " << i << " is {" << retIthVal << "}." << endl;
}
else if(returnvalue==1)
{
cout << "\nThe file is empty!" << endl;
}
else if(returnvalue==2)
{
cout << "Min is {" << minimum << "}." << endl;
cout << "Max is {" << maximum << "}.\n" << endl;
cout << "There aren't that many numbers in the file!" << endl;
}
return 0;
}
int processFile(ifstream& ifile, long i, long& retIthVal, long& minimum, long& maximum)
{
int number=0,
num;
ifile >> num;
maximum=num;
minimum=num;
while(ifile)
{
number++;
if(i==number)
{
retIthVal=num;
}
if(num>maximum)
{
maximum=num;
}
else if(num<minimum)
{
minimum=num;
}
ifile >> num;
}
if(i>number)
{
return 2;
}
if(number == 0)
{
return 1;
}
return 0;
}
|