Help w/ count from input file

Nov 12, 2016 at 12:56am
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
50
51
52
53
#include <iostream>
#include <fstream>

using namespace std;

int main()

{
	ifstream, inputfile, inFile;

	int num = 0, sum = 0, count = 0;
	double average;

	//Open the file.
	inputFile.open("numbers.txt");
	cout << "Reading data from the file.\n";

	//If the file successfully opened, process it.
	if (inputFile)
	{
		//Count the total number of
		//numbers in the file.
		while (inputFile >> num)
		{
			count++;
			sum += num;			
		}

		//Close the file.
		inputFile.close();

	}
	else
	{
		//Display an error message.
		cout << "Error opening the file.\n";
	}

		

		average = sum / count;

		cout << "There are " << num << " numbers in the file. \n";
		cout << "The sum of the numbers is " << sum << ".\n";
		cout << "Lastly the average is " << average << endl;

		



	return 0;
}
Last edited on Nov 12, 2016 at 1:40am
Nov 12, 2016 at 1:15am
average = sum / count;
You will need to cast either operands to a double, as integer division will truncate the fractional part. Other than that, I don't see anything that could cause any errors, assuming numbers.txt is formatted correctly.
Nov 12, 2016 at 1:24am
Well my sum and average work correctly its my count is way off.
Nov 12, 2016 at 1:33am
Your average most certainly does not work correctly, and your count is not way off. num is not count. You cannot use the two interchangeably.
Nov 12, 2016 at 1:40am
Well how come its giving me a count of 515 when there are only 200 entries ?
Nov 12, 2016 at 1:42am
Because 515 is the last entry and you are trying to use the last entry as the count.

cire wrote:
num is not count. You cannot use the two interchangeably.


Your stealth change to the code in the OP only fixed one instance of the problem. You have another on line 43.
Last edited on Nov 12, 2016 at 1:43am
Nov 12, 2016 at 1:51am
Thank you for the help. Switched the variables around and is working correctly.
Topic archived. No new replies allowed.