We have a file with integers. There's an integer on each line. We have to go through the file and find the minimum and maximum integer. Everything's clear on what to do, but I have a problem with the case when the file is empty.
Here's my code:
#include <iostream>
#include <fstream>
using namespace std;
void calculateMinMax(ifstream& inputStream, int& minNum, int& maxNum)
{
string currLine;
if(inputStream.ios::eof()) // code never enters this, even if file is empty !???
{
throw "EmptyFileException";
}
int currNum;
inputStream >> minNum;
maxNum = minNum;
while(getline (inputStream, currLine))
{
inputStream >> currNum;
if(currNum > maxNum)
{
maxNum = currNum;
}
if(currNum < minNum)
{
minNum = currNum;
}
}
inputStream.close();
}
int main()
{
int currNum, minNum, maxNum;
ifstream inputStream("numberFile.txt");
try
{
calculateMinMax(inputStream, minNum, maxNum);
cout << "Min: " << minNum << endl;
cout << "Max: " << maxNum << endl;
}
catch(...)
{
cout << "File is empty" << endl;
}
return 0;
}
The probelem is on the line where I'm checking whether the file is empty or not. I have no idea why that's happening, it just continues executing without exceptions even if it's empty. Any suggestions?