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.
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.
#include <iostream>
#include <fstream>
#include <vector>
usingnamespace 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);
}
elseif (!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 (unsignedint 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();