What I would do is first initialize an array of x elements.
Then using a loop, get the user input from the file and store it in a string or int variable and store that variable at the specific index of array.
so if a file is going to have 50 numbers,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int myArray[50];
for (int i = 0; i < 50; i++) // initializing an array
{
myArray[50] = i;
}
then use the same loop to get file input and store in array.
int getVal;
ifstream myFile("file.txt");
for (int i = 0; i < 50; i++) // initializing an array
{
myArray[50] = i;for (int i = 0; i < 50; i++) // initializing an array
{
myFile >> getVal;
myArray[i] = getVal;
}
int main()
{
ifstream inputFile;
string filename;
int size, sum, total;
int *myArray;
int average;
cout << "Enter File Name: ";
cin >> filename;
inputFile.open(filename.c_str());
if(inputFile){
myArray = new int [size];
for (int i = 0; i < size; i++){
inputFile >> myArray[i];
}
for (int i = 0; i < size; i++){
inputFile >> myArray[i];
total += myArray[i];
average = total / i;
From the code posted above, it seems that the number of items in the file is the first value in the file? Or maybe not?
To find the average, an array isn't actually needed. But still, for the sake of example we'll use one.
Instead of declaring all variables at the start, try to declare them as close as possible to where they are first used. Wherever possible, give an appropriate initial value too.
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
string filename; // get the file name
cout << "Enter File Name: ";
cin >> filename;
ifstream inputFile(filename.c_str()); // open the file
if (!inputFile) // check it was opened ok
{
cout << "Error opening file " << filename << '\n';
return 1;
}
int size = 0; // read how many numbers there are
inputFile >> size;
int * array = newint[size]; // allocate storage for the array
for (int i = 0; i < size; i++) // read all the numbers into the array
{
inputFile >> array[i];
}
double total = 0; // now find the total
for (int i = 0; i < size; i++) // of the values in the array
{
total += array[i];
}
double average = total / size; // calculate and display the average
cout << "The average is " << average << '\n';
delete [] array; // release the storage which was allocated with new
}