Read a list of random numbers from an input file and calculate statistics.

I need my program to read a list of numbers from and input file, random.txt, and calculate the following statistics on those numbers:

A. The number of numbers in the file.
B. The sum of all the numbers in the file.
C. The average of all the numbers in the file.
D. The largest number in the file.
E. The smallest number in the file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
   ifstream inputFile;

   int totalNum;
   int sumNum;
   int max;
   int min;
   float avg;
   
   inputFile.open("random.txt");
   
   cout << "Number of numbers: ";
   inputFile >> totalNum;
   cout << totalNum << endl;
  
   


This is what I have so far but I'm not sure if it is right. I can't get the input file to open.
Last edited on
Is the name of your file correct?
Is your file saved in the same folder as your project data?

Don't forget to close the file at the end of your code.
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
46
47
48
49
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

int main()
{
   int totalNumbers = 0;
   int sum = 0;
   int avg = 0;   
   
   ifstream inputFile;
   int number;
   
   inputFile.open("random.txt");
   
   if (!inputFile)
   {
      cout << "Error opening file." << endl;
   }
   else
   {
      while (inputFile >> number)
      {
         cout << number << endl;
      }
      
      inputFile.close();
   }
   
   while (inputFile.good())
   {
      inputFile >> number;
      ++totalNumbers;
      
      sum += number;
   }
   
   avg = sum / totalNumbers;
   
   cout << "Number of numbers is: " << totalNumbers << endl;
   cout << "The sum of the numbers is: " << sum << endl;
   cout << "The average of the numbers is: " << avg << endl;
   
   return 0;
}               
   


here is what I have.

It keeps printing out Error opening the file
Did you make sure the file was in same folder as your program?
Last edited on
Topic archived. No new replies allowed.