Avg and Std Dev from .txt file

Having trouble with standard deviation. It was mentioned that I might have to read the input file twice?

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <fstream>
#include <cmath>

using namespace std;

void calculate(ifstream& input_file, ofstream& output_file);

int main() {

	ifstream input_file;
	ofstream output_file;

	input_file.open("inputNumbers.txt");

	if (input_file.fail()) {
		cout << "Unable to open the input file\n";
		exit(0);
	}

	output_file.open("outputResults.txt", ios::app);

	if (output_file.fail()) {
		cout << "Unable to open the output file\n";
		exit(0);
	}

	calculate(input_file, output_file);

	input_file.close();
	output_file.close();

	cout << "\nDone reading and writing files.\n";

	cout << endl;

	return 0;
}
void calculate(ifstream& input_file, ofstream& output_file) {
	
	double sum = 0;
	double count = 0;
	double number;
	double average;
	double variance = 0;
	double standard_deviation = 0;

	while (!input_file.eof()) {
		input_file >> number;
		sum += number;
		count++;
	}
	average = sum / count;

	while (!input_file.eof()) {
		input_file >> number;
		variance += pow((number - average),2);
		variance /= count;
		count++;
	}
	standard_deviation = sqrt(variance);
	
	output_file << "The average of the numbers is " << average;
	cout << "The average of the numbers is " << average << endl;

	output_file << "\nThe standard deviation of the numbers is " << standard_deviation;
	cout << "\nThe standard deviation of the numbers is " << standard_deviation << endl;
}
I don't think you have to read the file twice, might be useful to have a few vectors though:

1. get your values and store them in a vector.
2. as you're pushing them into the vector, keep a running sum
3. calculate the average using this sum and the size of the vector
4. for each value in your vector take the average from this and square this (i'd store these values in another vector for debugging purposes.
5. Calculate the average of these values and take the square root of this.

Seems like you are try to doing this , but you don't need 2 while loops over the file.
Topic archived. No new replies allowed.