Greetings!
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;
exit(10);
}
// 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++; }
else
{ 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;
exit(20);
}
// close file stream fin
fin.close();
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!