Another Example

// A file whose name is input from the keyboard is created.
// The total number of integers wanted is input from the keyboard.
// Random integers are created and are placed in the file
// after it has been opened for output.
// This same file is then reopened, but for input this time.
// The integers are read in and the number of integers is counted.
// Another function computes the sum and the total number of integers read.

#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;

void createFile(string fileName, int size);
// create a file whose name is given by the string fileName
// and place random integers into the file.
// The number of integers is given by size.
// The file is closed at the end.

void total(string fileName, int& sum, int& Count);
// open a file whose name is given by the string fileName
// Compute the sum of the numbers in the file
// return the number of integers read.
// We imagine that the total number of integers in that file is unknown.
// The file is closed at the end.

int main( )
{
    string FileName;
    int Size, Sum = 0, Count = 0;

    cout << "Enter the name of the file you want to create: ";
    cin >> FileName;

    cout << "Enter the number of random numbers you want in the file: ";
    cin >> Size;

    createFile(FileName, Size);

    total(FileName, Sum, Count);

    cout << "The sum is: " << Sum << endl;
    cout << "The number of integers read is: " << Count << endl;

    if (Count != 0)
       cout << "The average number is: " << double(Sum)/double(Count) << endl;
    else
       cout << "The average is meaningless since there is no number in the file!"
                << endl;

    return 0;
}

void createFile(string fileName, int size)
{
    ofstream outs;
    int count = 0;

    outs.open(fileName.c_str( ));
    if (outs.fail())
    {
       cout << "Problem opening the file: " << fileName
                << " to output the random numbers.'\n'";
       exit(1);
    }

    // Should not use a do-loop since the file may be empty!
    while (count < size)
    {
       outs << rand( ) << endl;        count++;
    }

    outs.close( );
}

void total(string fileName, int& sum, int& count)
{
    ifstream ins;
    int number;

    ins.open(fileName.c_str( ));

    if (ins.fail())
    {
       cout << "Problem opening the file: " << fileName
                << " to input the random numbers. '\n'";
       exit(1);
    }

    while( ins >> number )
    {
       cout << number << endl;
       sum += number;
       count++;
    }

    ins.close( );

}