Hello! I got the first part of this (opening the file and getting the total amount of numbers in the file). However, I am stuck on how to now get the sum of the numbers in the file, as well as the average. Here's the question:
-------------
Download the following file from the Gaddis textbook Chapter 5 source code folder => random.txt
This file contains a long list of random numbers. Using your IDE-compiler create a new project and add this file to your project. Next write a program that opens the file, reads all the numbers from the file, and calculates the following:
A) The number of numbers in the file
B) The sum of all the numbers in the file (a running total)
C) The mean (average) of all the numbers in the file
------------------
Here is what I have so far:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main ( )
{
ifstream inputfile;
string filename;
int number;
//Get the filename from the user.
cout << "Enter the filename: ";
cin >> filename;
//Open the input file.
inputfile.open(filename.c_str());
int count=0;
while(!inputfile.eof())
{
inputfile>>number;
count++;
}
cout << "Number of numbers in the file is " << count << endl;
//If the file succesfully opened, process it.
if (inputfile)
{
while (inputfile >> number)
cout << number << endl;
//Close the file.
inputfile.close();
}
else
{
//Display an error message.
cout << "Error opening the file.\n";
}
}
|
OUTPUT:
Enter the filename: random.txt
Number of numbers in the file is 200
Program ended with exit code: 0
Any tips? Thanks! :)