Question: Question Write a C++ program that takes its input from a file of numbers of type double and outputs the average of the numbers in
Question
Write a C++ program that takes its input from a file of numbers of type double and outputs the average of the numbers in the file to the screen. The file contains nothing but numbers of type double separated by blanks and/or line breaks. If this is being done as a class assignment, obtain the file name from your instructor.
Can you add the ability to ask the user for the file name that needs to be opened and also correct anything that seems wrong?
#include
#include
using namespace std;
int main()
{
int n;
ifstream Input;
Input.open("c: umbers.txt"); //opening the file
if(Input.fail( )) //condition if file open fails
{
cout << "error opening input file"< return 1; } int c=0; while(!Input.eof()) //reading the numbers { Input>>n; sum=sum+n; //calculating the sum ++c; } double avg=0.0; avg=sum/c; //calculating the average cout<<"The average is: "< Input.close(); return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
