For some reason, when I display the list of numbers I just get one random number instead of the real list. Also, I get negative numbers in the total and average.
int main(){
ifstream inFile;
int num;
inFile.open(filename, ios::in);
(inFile >> num);
int myarray[50];
for (int x = 0; x < 50; x++)
myarray[x] = 0;
for (int x = 0; x < 50; x++)
inFile >> myarray[x]; // Bringing a list of numbers from a file already created.
int total = 0, count = 0;
double average = 0.0;
for (int x = 0; x < 50; x++)
{
total += myarray[x];
count++;
}
inFile.close();
average = static_cast<double>(total) / static_cast<double>(count);
if (total == 0 && average == 0.0) {
cout << "Data file is empty " << endl;
}
else
{
cout << endl << "Total :" << total << endl <<
"Average :" << fixed << setprecision(2) << average << endl;
cout << "File successfuly read" << endl;
}
PD: I added all the headers that are required to get file accesibility. (I did not wrote them here in order to avoid a huge page of code)
@Peter87 The file has 10 numbers on it, and for some reason, it only shows one digit that is not the first not last. Also, it's true. I never did anything with num.
Here is your program, with minor fixes. If you have any questions about it, please ask.
I'm not really sure if your data file actually contained 50 numbers or not, but your program tries to read in 50 at the start of your program. I changed it to read in one number at a time, then increase count if it didn't fail. That way, we know how many actual numbers there are.
#include <fstream>
#include <iostream>
#include <string>
#include <iomanip>
#include <windows.h>
using std::ifstream;
using std::fixed;
using std::setprecision;
using std::string;
using std::cout;
using std::cin;
using std::endl;
int main()
{
string filename = "NumList.dat";
int num, x, count = 0;
ifstream inFile(filename);
int myarray[50];
for (x = 0; x < 50; x++)
myarray[x] = 0;
x = 0;
while (inFile >> myarray[x])
{
count++; // To find how many data entries
x++;// increase x for next spot in myarray
}
cout << "Count = " << count << endl; // Display the count
inFile.close();
cout << "File successfuly read" << endl;
int total = 0;
double average = 0.0;
for (x = 0; x < count; x++)
{
total += myarray[x];
}
average = static_cast<double>(total) / static_cast<double>(count);
if (!total && !average)
{
cout << "Data file is empty " << endl;
}
else
{
cout << endl << "Total :" << total << endl;
cout << "Average : " << fixed << setprecision(2) << average << endl;
}
}
Yeah. But I was basing the 50 on what the OP shows in their program. (S)He created an array of 50, so I figured that would be the limit of what was to be read.