In: Computer Science
C++ Code While Loops.
Ask user for file and open file.
Do priming read and make a while loop that: 1. Reads in numbers. 2. Counts how many there is. 3. Also for every 10 numbers in the file, print out the average of those 10 numbers. Ex: (If 20 numbers in the file. "With 10 numbers the average is .... and With 20 numbers the average is" and EX for a file with 5 numbers "There are 5 numbers in this file with an average of ..."
After the loop calculate and print the average of all nums in the file.
Thanks for the question. Below is the code you will be needing. Let me know if you have any doubts or if you need anything to change.
If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions.
Thank You!
===========================================================================
#include<iostream>
#include<string>
#include<iomanip>
#include<fstream>
using namespace std;
int main(){
string filename;
cout<<"Enter filename: ";
getline(cin,filename,'\n');
ifstream infile(filename.c_str());
if(infile.bad() || !infile.is_open()){
cout<<"Error: Could not
open/read file: "
<<filename<<endl;
return 1;
}
int count = 0;
double totalAll = 0;
double num;
while(infile>>num){
count+=1;
totalAll+=num;
if(count%10==0){
cout<<setprecision(2)<<fixed<<showpoint;
cout<<"With "<<count<<" numbers the average is
"<<totalAll/count<<endl;
}
}
cout<<"There are "<<count;
cout<<setprecision(2)<<fixed<<showpoint;
cout<<" numbers in the file with an average of
"<<totalAll/count<<endl;
infile.close();
return 0;
}
=======================================================================