In: Computer Science
C++ and there has to be a FUNCTION to get all the integers.
Suppose there is a file called MidtermExam.txt that is full of integers. Write a program that complies with the following instructions:
Write a function that you will later call in main. Your function
is to read from the file all the integers and print to the screen
the total of all the numbers in the file, and the average with 2
significant digits after the decimal point.
If your program is unable to access the file, you should tell the
user that (show a message) and then shut down the program.
When you are done reading from the file, give the commands to close
the file.
Note: I did not forget to attach an input file. You can use the one
in lecture 6's module if you want, or create dummy file yourself. I
am interested in your code.
Hello!
I have used the function so that
Some method used in the code
ifstream is used to read files as our code requires only reading operation we used ifstream
ifstream file; // file is a variable name
file.open("fileName.ext"); // this opens the file mentioned
file.is_open() returns true if file is opend, or else false if we cannot able to open or access it.
file.is_eof() // returns true when the cursor reaches at the end of the file ,
file >> num1 // moves the data integer to num1 from the file
So finally at the end of the we should close the file
file.close() // closes the file
CODE:
#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;
void readFileCalTotalAvg()
{
int data[1000], num = 0;
double total = 0.0, avg;
// ifstream for reading file
ifstream file;
// open method to open file
file.open("MidtermExam.txt");
// loop conftinues till it reaches the end of the file
if (!file.is_open())
{
cout << "File cannot be accesed!" << endl;
}
else
{
while (!file.eof())
{
// data from file copies to data[num]
file >> data[num];
// stores num of integers in file
num++;
}
// this is because there's an extra line in the text file
num--;
// closing a file
file.close();
// printing the data stored from file in data array
//for (int i = 0; i < num; i++)
// cout << data[i] << endl;
// iterarting over each integer and add to total
for (int i = 0; i < num; i++)
total += data[i];
// display the total of all integers in the file
cout << "Total of all the marks: " << total << endl;
// calculates the average of all integers
avg = total / num;
// displays the average of all the integres
cout << "Average marks: ";
// printing only 2 digits after decimal point
printf("%.2f\n", avg);
}
}
int main()
{
// calls the function which read the file and calculates the total and average
readFileCalTotalAvg();
return 0;
}
OUTPUT:
When Data is in horizontal
When data is in vertical order
When file cannot be accesed
Hope this helps and clear.
I strive to provide the best of my knowledge so please upvote if you like the content.
Thank you!