I need C++ code for the following problem. I have the text file mentioned in the
ID: 664080 • Letter: I
Question
I need C++ code for the following problem. I have the text file mentioned in the problem if you need it. I can't attach it here but I can attach to an email if necessary.
Working with files – You will need the text file Random.txt that can be found in the Content area of the course under Week 5. The file contains a list of random numbers. Write a program that opens the file and reads all the numbers from the file, and calculate/determine the following:
Counts how many numbers were read from the file
The sum of all the numbers in the file (a running total)
The average of all the numbers in the file
Determine the lowest and highest values in the file
The program must validate that the file was opened before reading from the file.
If file does not exist display a message telling the user that the file could not be opened and exit the program.
Explanation / Answer
#include <iostream.h>
#include <fstream.h>
#include <cstdlib.h>
int main()
{
int i,sum=0,count=0,low=0,high=0;
float avg;
ifstream inFile;
inFile.open("Random.txt",ios::in);
if (!inFile)
{
cout << "The file could not be opened "<< endl ;
exit(1);
}
cout << "Opened File for reading." << endl;
while (inFile >> i)
{
sum=sum+i;
count++;
if(i<low)
low=i;
if(i>high)
high=i;
}
avg=sum/count;
cout << "Numbers read from file are " << count <<endl;
cout << "Sum Of Numbers in a File is "<< sum <<endl;
cout << " Average of numbers in file is " << avg <<endl;
cout << " Lowest of numbers in file is " << low <<endl;
cout << " Highest of numbers in file is " << high <<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.