2,3,4,5,6,9,4,3,2,1,12,16,19,18,11,19,18,23,21,13,16,18,19,3,4,5,6,9,4,12,16,19,18,11,19,18,23, 21,13,16,18,19,3,4,5,6,9,4,1,12,16,19,18,11,19,18,23,21,13,16,18,19,3,4,5,6,9,4,12,16,19,18,11, 19,18,23,21,13,16,18,19,3,4,5,6,9,4,4,5,6,9,4,3,2,1,12,16,19,18,11,19,18,23,21,13,16,18,19,3,4,5, 6,9,4,12,16,19,18,11,19,18,23,21,13,16,18,19,3,4,5,6,9,4,1,12,16,19,18,11,19,18,23,21,13,16,18, 19,3,4,5,6,9,4,12,16,19,18,11,19,18,23,21,13,16,18,19,3,4,5,6,9,4
Please write a C ++


The program uses fstream header file to read and write from the text file, data.txt.
An array is used to read and write to the file using a loop.
Since the size of array is unknown sizeof() method is used to calculate the size of array.
Since the size of array is unknown data type long is used instead of int.
// Code for writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
fstream myfile;
myfile.open("data.txt", ios::out | ios::in);
long a[] = {2,3,4,5,6,9,4,3,2,1,12,16,19,18,11,19,18,23,21,13,16,18,19,3,4,5,6,9,4,12,16,19,18,11,19,18,23,
21,13,16,18,19,3,4,5,6,9,4,1,12,16,19,18,11,19,18,23,21,13,16,18,19,3,4,5,6,9,4,12,16,19,18,11,
19,18,23,21,13,16,18,19,3,4,5,6,9,4,4,5,6,9,4,3,2,1,12,16,19,18,11,19,18,23,21,13,16,18,19,3,4,5,
6,9,4,12,16,19,18,11,19,18,23,21,13,16,18,19,3,4,5,6,9,4,1,12,16,19,18,11,19,18,23,21,13,16,18,
19,3,4,5,6,9,4,12,16,19,18,11,19,18,23,21,13,16,18,19,3,4,5,6,9,4};
int size = sizeof(a) / sizeof(a[0]);
cout << size;
if (myfile.is_open())
{
for(int count = 0; count < size; count ++)
myfile << a[count] << " " ;
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
// Code for reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
long nums[172];
int sum;
fstream myfile;
myfile.open("data.txt", ios::in | ios::out);
if (myfile.is_open())
{
for (int i=0; i<172; i++)
{
myfile>>nums[i];
//cout<<nums[i]<< " ";
}
myfile.close();
}
else cout << "Unable to open file";
sum = 0;
for (int i=0; i<172; i++)
{
cout<<nums[i]<<" ";
sum += nums[i];
}
int mean = sum / 74;
cout<<"\n Mean: "<<mean;
return 0;
}
Step by step
Solved in 3 steps with 1 images









