Newbie with another question for the experts...I am teaching myself C++ and have spent a fair amount of time reading on this site to help better understand how things should work. Along the way I have read about functional decomp and could use some suggestions on the code below. My initial thought was to create a function for user input, a function to perform the calculations and a function to display results.
Take it easy on my as I am self taught and just trying to learn but I do appreciate the help!
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <iomanip>
constint MAX_MONTHS = 20; //max number of months to import per supervisor
int main()
{
usingnamespace std;
char infilename[16];
char rerun;
int numRecords;
double total = 0; //initialize accumulator to 0
double records[20]; //supervisor specified the array would have a max
value of 20, so that is what I used to setup the array.
double maxValue; //max monthly salary value
double minValue; //min monthly salary value
ifstream inStream;
ofstream outStream;
cout << "Enter the input file name (maximum of 15 characters):\n";
cin >> infilename; //variable to hold the name of the HR input file
cout << "This application will read the salary data from the file and
compute low, high, and average salary amounts. \n";
inStream.open(infilename);
if (inStream.good())
{
inStream >> numRecords; //1st line in file tells how many months of data are in the file.
cout <<"This file contains "<<numRecords<<" months worth of
salary data." <<endl;
inStream >> records[0]; //put remaining data from infilename in array starting with index 0.
minValue = records[0];
maxValue = records[0];
for (int i = 1; i < MAX_MONTHS && i < numRecords; i++)
{
inStream >> records[i];
}
for (int i = 0; i < MAX_MONTHS && i < numRecords; i++)
{
total=total+records[i]; //add salary data for averaging employee salary.
if (minValue>records[i])
{
minValue = records[i];
}
elseif (maxValue<records[i])
{
maxValue = records[i];
}
}
inStream.close();
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout <<"The lowest monthly salary earned was $"<< minValue <<endl;
cout <<"The highest monthly salary earned was $"<< maxValue <<endl;
cout <<"The average monthly salary earned was $"<< total/numRecords <<endl;
return 0;
}
}
you can take the file I/O and remove all of it into a function, and have that function return the # of records it reads along with min and max. leave the print statement for that in main, it does not belong in the function. (line 38).
if you want to move the input/output to functions you can do that as well.
this program is not really showing the concept well. The idea of functions is that code you repeat multiple times be moved out, as a priority. The secondary idea is breaking it up into logical segments that are easier to understand, which is what we are doing here.