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; 
}

Recommended Answers

All 6 Replies

Your passing by reference is fine for AverageNum(), but you do seem to be calling it before the file has been opened. Why do you have two calls to AverageNum()?

Yes I do believe I have two calls for AverageNum() because I also have to return the value/data for average in the user defined function and then display it in the int main () for switch case B

Sorry I don't get that. It still doesn't make sense to me that you are calling AverageNum() twice in switch case B. I suggest you remove the first call and try it again.

1. The AverageNum function (incorrect, see #2 below) has a side effect: the input stream is in eof (or failed) state after this function call. You din't correct this state: din't close stream, din't rewind (reset read pointer) it - do nothing. After absolutely senseless 1st call in B choice the 2nd call will never get the average: you can't get numbers from failed stream. Moreover, see what happens below:

2. You didn't check stream input correctly in your functions. For example, if input stream has no numbers (binary file or the first item in the first line is not a number) or is in failed state (see #1 above) then AverageNum returns undefined result or raises exception (zero divide). You don't initialize count local variable, it has unpredictable value. Because this initial value must be 0 the function will divide 0/0 if the 1st input failed.

// No need in ifstream: use more general istream
double Average(istream& is)
{
    double number, sum = 0.0;
    int count0;
    for (count = 0; is >> number; count++)
        sum += number;
    return count? sum/count: 0.0;
}

3. Think about Average function without side effect (tip: ifstream& parameter needed)...

4. Change CountWords main loop to:

for (count = 0; inFile >> word; count++)
    ;
// or equivalent
count = 0;
while (inFile >> word)
    count++;

No need in two input statement here.

5. Change CountWords signature to:

int CountWords(const string& filename);

Now you can use string literal arguments.

Thanks for your tips

My first wordcount function is fine you code is just more efficent Thanks!

however I just need one call so i can display the average back in main which I keep getting a decimal number which shouldnt happen because my file containing the numbers average is 3

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.