Short program build help

Im having trouble starting or building this program for my c++ class pease help someone.

The program i need to run needs to open a file that contains a series of numbers reaads 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 Average of all the numbers in the file

And displays all of these.

File name TopicD.cpp
Without testing:

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
#include <iostream>
#include <fstream>
#include <cstdlib>
 
int main()
{
   const char *name = "TopicD.cpp";
 
   std::ifstream input_file( name );
 
   if ( !input_file )
   {
      std::cerr << "Error: file " << name << " can not be opened" << std::endl;
      std::exit( 1 );
   }
 
   int sum = 0;
   int count = 0;
   int number;
 
   while ( input_file >> number ) sum += number, ++count;
 
   if ( count != 0 )
   {
      std::cout << "There are " << count << " numbers in the file" << std::endl;
      std::cout << "The sum of the numbers is " << sum << std::endl;
      std::cout << "The average of the numbers is " << sum / count << std::endl;
   }
 
   return 0;
}
Watch out for integer division on line 27.
@booradley60
Watch out for integer division on line 27


What is the problem? Why the average can not be an integer number for a sequence of integers?
Last edited on
Well if the input file contains
6 7 7 7 7
integer division gives the average as 6, which is misleading.
does the file that im opening have to be in a specific place?
or how does that work in this program? and the file name that im trying to open is called random.txt
@Chervil
Well if the input file contains
6 7 7 7 7
integer division gives the average as 6, which is misleading.


There is nothing misleading because you are dealing with integers.
For median and mode I would agree with you, but the average could still have fractional data even if all the inputs are integers.
@booradley60
For median and mode I would agree with you, but the average could still have fractional data even if all the inputs are integers.


I do not argue because I do not see the subject of the discussion. I only see that you have some problems with integers. It is your problems not main. You personally can use a floating type but I prefered to use the integer type for the average of a sequence of integers.
I only see that you have some problems with integers.
My problem with integers is that in many cases they cannot faithfully represent the actual value of the average of a sequence of integers.

It is your problems not main.
It is a problem to anyone who takes the word 'average' in this case to imply 'arithmetic mean'.

@tycastill0
You can try specifying the entire path to your file. Otherwise, the executable will look in certain directories depending on your environment.
Last edited on
Topic archived. No new replies allowed.