0

So I'm writing a file that collects a list of integers from a .dat file and counts how many odds and evens there are.

The code I wrote for this works for the most part. But there is one obscure scenario where it fails. If a line in the .dat file ends in an even number it will count 1 more even and 1 less odd then its supposed to.

Any ideas as to whats happening? what's I tried:

cout << "What is the name of the input file? ";
cin >> fileName;

infile.open(fileName);
if (infile.fail())
{
    cout << "Error opening " << fileName << endl;
}
else 
{
    infile >> number;
    while (!infile.eof())
    {
        count1++;
        infile >> number;

        if (number % 2 != 0)
        {
            odd++;
        }
        else
        {
            even++;
        }
    }
}

infile.close();


cout << "The number of integers is: " << count1 << endl;
cout << "There are " << odd << " odd integers and " << even << " even integers" << endl;

system("pause");
return 0;
}
A1Gard
  • 3,631
  • 3
  • 25
  • 49
Josh
  • 1

1 Answers1

2

The problem lies in use of

while (!infile.eof())

to decide when to terminate the loop. See Why is iostream::eof inside a loop condition considered wrong?.

Use the following:

else
{
   while ( infile >> number )
   {
      count1++;

      if (number % 2 != 0)
      {
         odd++;
      }
      else
      {
         even++;
      }
   }
}
R Sahu
  • 196,807
  • 13
  • 136
  • 247
  • Thanks so much that fixed it. – Josh Feb 03 '18 at 03:40
  • @Josh, glad o hear it. I hope you read the post I linked to to fully understand the solution I suggested. – R Sahu Feb 03 '18 at 03:45
  • When you find that a question exhibits a problem that's already been asked about, flag the duplicate, don't write another, less complete answer. – Ben Voigt Feb 03 '18 at 06:38
  • @BenVoigt. I agree in principle. I thought an answer that specifically addresses how the OP's code can be rearranged would be helpful. – R Sahu Feb 03 '18 at 07:53