I have to do this user defined function
return type: double
parameters: one (1)
type: ifstream (by reference); variable used to read the file
description assume the file has already been opened successfully in main()
read through the file, average the numbers and return the average to main() to be printed
this is my complete code so far obviously my error is passing reference correctly because it just exit the prog when I do this option which is option B it the second user function at the bottom the first user defined function is fine
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
//Function Prototype for Choice A
int CountWords (string FileName);
//Function Prototype For Choice B
double AverageNum ( ifstream& ReadFile);
int main ()
{
char choice;
int WordCount;
string FileName;
ifstream inFile;
double average;
do{
cout<<"A - count words in a while\n";
cout<<"B - average the numbers in a file\n";
cout<<"C - min and max\n";
cout<<"D - count numbers in a file\n";
cout<<"E - sum integers in a range\n";
cout<<"Q - QUIT\n";
cout<<"Enter choice: ";
cin>>choice;
switch (choice)
{
case 'A':
cout<<"Enter name of the input file: ";
cin>>FileName;
//Function Call
WordCount = CountWords (FileName);
cout<<"Word Count: "<<WordCount<<endl;
cout<<endl;
break;
case 'B':
cout<<"Enter name of the input file: ";
cin>>FileName;
AverageNum(inFile);
inFile.open(FileName.c_str());
if (inFile.fail()){
cout<<"Error Reading File\n";
return 0;
}
average = AverageNum (inFile);
cout<<"Average of numbers in file "<<average<<endl;
cout<<endl;
break;
case 'C':
break;
case 'D':
break;
case 'E':
break;
case 'Q':
cout<<"Now Exiting\n";
break;
default:
cout<<"Invalid choice\n";
break;
}
}
while (choice != 'Q');
system("Pause Screen");
return 0;
}
//Function Definition for Choice A
int CountWords (string FileName)
{
ifstream inFile;
string word;
int count;
count = 0;
inFile.open(FileName.c_str());
if (inFile.fail()){
cout<<"Error Reading File\n";
return 0;
}
inFile>>word;
while(inFile){
count++;
inFile>>word;
}
return count;
}
//Function Definition for Choice B
double AverageNum (ifstream& ReadFile)
{
int count;
double sum, average, num;
sum = 0;
ReadFile>>num;
while(ReadFile){
count++;
sum = sum + num;
ReadFile>>num;
}
average = (sum / count);
return average;
}