This:
Code:
while (!infile.fail() && !infile.eof())
{
infile>>number;
... is wrong. You need to test the read operation for success and continue if things are OK. You should avoid using end-of-file tests to control your loops wherever possible. In your case, reading the last number from the file puts you at the end of the file but does not trigger the setting of the end-of-file flag. This means that at the top of your loop when you go back to test if you're at the end of the file (!infile.eof()), the test returns false - which gets turned into true due to the negation (!) - even though you are physically at the end of the file. You therefore attempt to read one more time (infile>>number) which then fails, it is only then that the end-of-file flag gets set. But, it's already too later since you're already inside the loop acting as if everything went fine. Since the read operation failed, number remains unchanged still holding whatever value it had during the last successful read operation and this messes up your counts since because you are then processing that last result twice.
Like I said, you need to test the result of the read operation and only continue if that read is successful. You do that by replacing what you wrote above with this:
Code:
while(infile >> number)
{
If the read operation fails, the stream (infile) will go into an error state after which no more reads can be made from it. The extraction operation on that stream returns the stream object itself (infile >> number actually returns the stream infile). In the context of the above modified while loop, the returned stream can then be tested directly as either true or false.
This:
Code:
if (number%2==0)
{
counter=0;
counter++;
sum_even=sum_even+counter;
}
if (number%2!=0)
{
counter=0;
counter++;
sum_odd=sum_odd+counter;
}
Can be written better as:
Code:
if (number%2==0)
{
++sum_even;
}
if (number%2!=0)
{
++sum_odd;
}
And actually since a number is either even or odd, if it's one it is certainly not the other so we really only need to make one single test to decide which one it is:
Code:
if(number%2)
++sum_odd;
else
++sum_even;
We can shorten this further using a single line statement involving what's known as the ternary operator (?:) as such:
Code:
(number%2) ? ++sum_odd : ++sum_even;
...where ++sum_odd only gets executed if number%2 is true (number is odd) and ++sum_even only gets executed if number%2 is false (number is even).