LAB 09A - READING DATA FILES

Concepts

The focus of this assignment is on one concept: how to read data from an "input file stream" or ifstream object. This lab will be submitted with Homework 9.

Working with Data

Today's class discussed how data is often treated as "streams" of information that can be read a piece at a time. The files we will read in CSCI 261 are simple text files; for lab today, the simple text file contains a series of numbers. Remember that whenever you work with a file stream as input, we call them ifstream objects.

There will always be four things you will do whenever working with an ifstream. Open the file, check for an error, read its data, and close the file. The typical pattern for this is as follows:

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

int main() {
        int age;
        ifstream myCatsAges("filename"); // declare ifstream object and open the file

        // check for an error
        if ( myCatsAges.fail() ) {
           cerr << "Error opening input file";
           exit(1);
        }

        // read the data and do something with it
        while ( !myCatsAges.eof() ) {
            myCatsAges >> age;
            cout << "One cat is " << age << " years old.\n";
        }

        myCatsAges.close(); // close the file

        return 0;
}

Remember, once you have an ifstream object (like myCatsAges shown above) you use it in a manner similar to using cin.

Instructions

For this assignment, download this text file that contains the populations of America's cities. (Place this file at the project level, which should be the same directory as your main.cpp file. You should see both your input file AND a .vcxproj file in the same directory.) Your goal is to create a program that will read the data in the file, and then print the average population. The contents of the file look like this (but with many more numbers):

12345
8675309
etc...

The interaction for this program is simple. When executed, the output should be:

The average population of America's 275 cities is 306696.

If your program generates the above output, then your program is likely correct.

Your program must read the data in the provided file using the typical "data reading" boilerplate: open the file, check for an error, use a while loop to read sucessive data from the stream, and close the file.

NOTE: Your program should not explicitly divide by the number 275 when computing the average. It should count the number of data entries in the file. In other words, your program should correctly compute the average when given a data file of any number of records.