a. Store the following data in a file named numbers.dat:
5 96 87 78 93 21 4 92 82 85 87 6 72 69 85 75 81 73
b. Write a C++ program to calculate and display the average of each group of numbers in the
file created in Exercise 11a. The data is arranged in the file so that each group of numbers
is preceded by the number of data items in the group. Therefore, the first number in the
file, 5, indicates that the next five numbers should be grouped together. The number 4
indicates that the following four numbers are a group, and the 6 indicates that the last six
numbers are a group. (Hint: Use a nested loop. The outer loop should terminate when the
end of file has been encountered.)
Program mi zadnji rezultat ispisuje dva puta, zašto?
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream outFile;
ifstream inFile;
int sum = 0, myArr[10];
double avg;
int arr[] = { 5, 96, 87, 78, 93, 21, 4, 92, 82, 85, 87, 6, 72, 69, 85, 75, 81, 73 };
int size;
outFile.open("numbers.dat");
inFile.open("numbers.dat");
size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < size; i++)
{
outFile << arr[i] << " ";
}
outFile.close();
cout << "Data are stored in file!!!\n";
if (inFile.fail())
{
cout << "File couldn't be opened!!!" << endl;
exit(1);
}
else
{
while (!inFile.eof())
{
inFile >> size;
for (int i = 0; i < size; i++)
{
inFile >> myArr[i];
cout << myArr[i] << " ";
sum = sum + myArr[i];
}
cout << "\nSum: " << sum << endl;
avg = sum / size;
cout << "Avg values: "<< avg << endl;
sum = 0;
cout << endl;
}
inFile.close();
}
return 0;
}