In: Computer Science
To read in a number from a file as an integer is very simple.
(Assuming our file is defined as myInput; int mynum; myInput >> mynum;
The file name should be myNum.txt
A sample run of the program: The min is: 40 The max is: 90 The total is: 180
The average is: 60 The number of records read in was: 3 This run used 90 40 50 as its test input.
A couple of things to keep in mind, you must handle two other conditions. The file does not exist or cannot be opened. The file opens but does not contain data. Make sure you have error messages for these conditions. The other thing that you have to handle is that the numbers might include negative numbers or very large numbers so using 0 as a starting point for max or some high number for min may not work. For testing create your own input. Think about what we said for easy testing then try with more numbers. Look at the work we did in class for hints on file handling. I suggest you work through your logic (i.e. pseudocode/algorithm) before coding.
Solution:
Code:
#include<fstream> // include statement for file operations.
#include<iostream> // include statement for I/O operations.
using namespace std;
int main() {
int cnt=0; // counter variable
ifstream file("myNum.txt"); // opens the file.
int min=INT16_MAX; // min variable assigned to max value.
int max=INT16_MIN; // max variable assigned to min value.
int val; // variable to store values after reading from file.
int total=0; // total variable initialised to 0.
while (file >> val){
cnt++; // increments counter variable.
total+=val; // adds the value read from the file.
if(min>val)
min=val; // updates min variable.
if(max<val)
max=val; // updates max variable.
}
cout<<"The min is: "<<min<<endl;
cout<<"The max is: "<<max<<endl;
cout<<"The total is: "<<total<<endl;
cout<<"The average is: "<<total/cnt<<endl;
//close the file
file.close();
}
Code screenshot:
Code output screenshot: