Write a program that reads a file of numbers and output all the numbers and the average of the numbers into another file

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

Write a program that reads a file of numbers and output all the numbers and the average of the numbers into another file

Post by answerhappygod »

Write a program that reads a file of numbers and output all
the numbers and the average of the numbers into another file. The
input file name is txt1In.txt and it contains 6 numbers of type
double separated by blanks or line breaks. Name the output file
txt2Out/txt.
I seem to have confused myself in outputting the average I was
able to output the list of numbers just confused where to put the
average please help?
int main()
{//declaration
double n;
double number;
ifstream in_Stream;
ofstream out_Stream;
in_Stream.open("twelveTwoIn.txt");//opening
input file
if(in_Stream.fail( ))//if input file doesn't
exist
{
cout << "Error opening
input file"<<endl;
exit (1);
}
out_Stream.open("twelveTwoOut.txt");//creating output
file
if(out_Stream.fail( ))
{
cout << "Error opening
output file"<<endl;//if an error creating
exit(1);
}
//processing 6 numbers writing them to output
file
for (int i = 0; i < 6; i++)
{
in_Stream >> number;
out_Stream << number <<
endl;
}
//calculating the average
double sum=0;
int count=0;
while(!in_Stream.eof())
{
in_Stream >> n;
sum += n;
count++;
}
double avg=0;
avg = sum/double (count);
//Writing to output file
out_Stream << "The average: " << avg
<< endl;
//output to screen
cout << "The average is: " << avg
<< endl; //output to screen as a checker
in_Stream.close();
out_Stream.close();
return 0;
}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply