I've been working on this program for the past couple of hours now, and I cant seem to get it right. I'm supposed to write a program that reads in integers from a text file, and then find the sum of the integers. The problem I'm having is with finding the sum. Here is my program thus far:

//File name: readData.cpp
//Created by: Ricardo Renta
//Created in: 11/1/11

#include <cstdlib> // function exit() is in cstdlib
#include <fstream> // class ofstream() is in fstream
#include <iostream>
#include <string>
using namespace std;

int main()
ofstream fout;
ifstream fin; // declare an input file stream
string name;
int x(0);
double avg(0.0);
int sum(0);

cout << "Enter file name: ";
cin >> name;

// open file file_name for input
fin.open(name.c_str(), ios::in);

// check if file is opened for input
if (!fin.is_open())
cerr << "Unable to open file " << name << endl;

// read text from file
fin >> x;
int ne(0);
int oe(0);
while (!fin.fail())
cout << "Read integer: " << x << endl;
fin >> x;

sum += x;

if (x%2 == 0)
{ ne++; }

{ oe++;}


avg = sum/(ne+oe);

cout << "The sum if the integers is:" << sum << endl;
cout << "The average of the integers is:" << avg << endl;
cout << "The number of even integers is:" << ne << endl;
cout << "The number of odd integers is:" << oe << endl;

// check for error
if (!fin.eof())
cerr << "Error reading file " << name << endl;

// close file stream fin

return 0;

if anyone could point me in the direction that I need to go, that would be very much appreciated! I am not looking for a handout, just a hint :)

Thank you!

6 Years
Discussion Span
Last Post by maynardjk13

The first problem is you read a number into x and print it out, but don't add it to the sum. The second problem is using fin.fail() as the loop condition, it's basically the same as using feof(), which is wrong.

Try this instead:

// read text from file
int ne(0);
int oe(0);

while (fin >> x) {
    cout << "Read integer: " << x << endl;

    sum += x;

    if (x % 2 == 0)

thank you! I would like a better understanding of this, however. Why is using feof() (which is the equivalent of !fin.fail()) as the loop condition wrong?


Why is using feof() (which is the equivalent of !fin.fail()) as the loop condition wrong?

I posted a link. Basically it's a timing issue. The error flags aren't set until after you try and fail to read from the stream. Unless the loop contains a further sanity check, you'll be working with data from the previous iteration. It's a "the last record is processed twice" situation.

Edited by Narue: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.