-2

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?

Mr. Nicky
  • 1,519
  • 3
  • 18
  • 34

2 Answers2

2

There is a more simple solution. You can read numbers directly to int using >>. It returns false when EOF is reached.

void calculateMinMax(ifstream& inputStream, int& minNum, int& maxNum)
{
  int currNum;

  if(inputStream >> currNum)
  {
    maxNum = currNum;
    minNum = currNum;
  }
  else // there is not first number
  {
    throw "EmptyFileException";
  }

  while(inputStream >> currNum)
  {
    inputStream >> currNum;

    if(currNum > maxNum)
      maxNum = currNum;

    if(currNum < minNum)
      minNum = currNum;
  }

  inputStream.close();
}
Pavel
  • 5,374
  • 4
  • 30
  • 55
2
if(inputStream.ios::eof()) // code never enters this, even if file is empty !???
{
    throw "EmptyFileException";
}

Very simple reason for this. The file stream has no way of knowing that you have reached the end of the file until it finds the end of the file. The only way to find the end of the file is to read from the file until a read fails because the end has been reached.

If the file is empty, the first read will fail and the EOF bit will be set. You can check this with a peek as covered in Checking for an empty file in C++

Off topic: This is clunky: inputStream.ios::eof(). inputStream.eof() is sufficient and possibly safer on the off chance std::ifstream overrides eof() with something more substantial than a check of the EOF bit.

Community
  • 1
  • 1
user4581301
  • 33,082
  • 7
  • 33
  • 54