Outputting file data

I have two questions with this code here. I can get the file to open and display the numbers one right after the other, I am not sure how to format them so they display correctly. My second question is I am supposed to have an array that can handle up to 100, but I have to limit it in order to show the correct results; how can I make is so that it will handle more without limiting i.

100.8
120.4
121.4
111.9
123.4
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>

using namespace std;

int main()
{
	double myArray[100];
	ifstream myFile("C:\\Users\\UKELLKI\\Downloads\\voltages.txt");
	if (myFile.is_open())
	{
		for (int i = 0; i < 5; i++)
		{
			myFile >> myArray[i];
			cout << myArray[i];
		}
		myFile.close();
	}
	else
		cout << "unable to open voltages";

	system("Pause");
	return 0;
}
1) your problem is that you are writing your number without any delimeters so they are showing as bunch of digits and dots. Use something like cout << myArray[i] << '\n';

2) You need either to store your array current size, or use some automatic container which does not have the problem of containing more elements than needed or that you cannot fit some elements. Default solution: vector.
Here is the code I have so far, I have it displaying correctly, but I cannot figure out how to get an average of the function. I am wondering if there is a better way to format my mathematical equation, for lines 39-41.

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
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
	vector<double> myArray;
	ifstream myFile;
	myFile.open("C:\\Users\\UKELLKI\\Downloads\\voltages.txt");
	if (myFile.fail())
	{
		cout << "\nCould not open the file ... check to see if it exists";
		return 0;
	}

	double myData;

	do
	{
		myFile >> myData;
		if (myFile.good())
		{
			myArray.push_back(myData);
		}
		else if (!myFile.eof())
		{
			cout << "\n There was a problem reading the file";
			return 0;
		}
	} while (!myFile.eof());

	double sum = 0.00;
	double avg = 0.00;

	for (unsigned int i = 0; i < myArray.size(); i++)
	{
		cout << myArray[i] << '\n';
		sum += myArray[i];
		avg += (sum/i);
	}
	cout << "\nThe sum of the numbers in the file is " << avg << endl;

	system("Pause");
	return 0;
}
Average is a sum of all elements divided by amount of elements.
You are calculating sum in your loop and you can get amount of elements using size().
So remove everything related to average and add this line after the loop:
double average = sum / myArray.size();
Thanks for your help.
Topic archived. No new replies allowed.