C++ program that reads a file of integers and………

I'm completely stuck. I need to make a program in c++ that reads in a file (txt) of integers and prints the sum, average, and the number of even and odd integers.If the file contains letters, than the program should print an error message. The steps to complete this are listed:

1. Prompt and readin te input file name the file for output

3. check if the file was successfully opened for output

4. Read every integer in the file, computing the sum and counting even and odd integers

5. The same integer can appear more than once

6. Close the output file stream

7. Compute the average

8. Output the average of the integer

Here is what I have so far


// function exit() is in cstdlib
#include // class ofstream() is in fstream
#include // used for calculations
#include // used for reading strings
using namespace std;

int main()

int sum; // Delcaration of sum for average
double average, n; // Declaration of average and total
int even; // Declaration of even intergers
int odd; // Declaration of odd integers
int len; // length of file

ifstream fin; // Declaration of an input file stream
string file_name;
int x;

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

// Open file file_name for input, ios::in);

// check if file is opened for input

if (!fin.is_open())
cerr << "Unable to open file " << file_name << endl;

// read text from file

fin >> x;

for (x=0; x<=10000; x++) // it doesn't actually have to be 10000, I just can't figure out how to tell it to stop when the entire file as been read
sum = sum + x;

average= (double)sum/x;

if (!

cout << "Sum = " << sum << endl;
cout << "Average = " << average << endl;
cout << "Number of even integers = " << even << endl;
cout << "Number of odd integers = " << odd << endl;

fin >> x;

// Error check

if (!fin.eof())
cerr << "Error reading file " << file_name << endl;

// close file stream fin



Something is screwy with the calculations and I'm really not sure how to fix it.


Expert Solution
No answers

Submit Your Answer