Sample Program: File Input

//  This program calculates the average of a set of exams.
//  The program will read in exactly 4 grades from a file, then calculate
//  and print the average. The input data is stored in a file named
//  grades.dat. You can choose any filename you want, but use .dat for the
//  file extension.

#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>

int main()
{
   int grade1;
   int grade2;
   int grade3;
   int grade4;
   int numberOfGrades;
   int totalGrades;
   float averageGrade;
   ifstream inputFile;

//  open the input file
   inputFile.open("grades.dat");

//  read in the grades, total them, and count how many grades there are
   inputFile >> grade1;
   inputFile >> grade2;
   inputFile >> grade3;
   inputFile >> grade4;
   cout << "The grades are: " << grade1 << "  " << grade2 << "  " << grade3
        << "  " << grade4 << endl;
   totalGrades = grade1 + grade2 + grade3 + grade4;

//  calculate and print the average
   averageGrade = float(totalGrades) / 4;
   cout << setiosflags(ios::fixed);
   cout << setiosflags(ios::showpoint);
   cout << setprecision(1);
   cout << "The average grade for the exam is :  " << averageGrade << endl;
}

Sample Execution: Contents of grades.dat

81
92
77
71

Sample Execution: Output

The grades are: 81  92  77  71
The average grade for the exam is :  80.2


Email Me | Office Hours | My Home Page | Department Home | MCC Home Page

© Copyright Emmi Schatz 2002