Sample Program: File Input - Read Until Sentinel

//  This program calculates the average of a set of exams.
//  The program will read in grades from a file, stopping when it reads the
//  sentinel (-999). Then it will calculate and print the average.
//  The input data is stored in a file named gradesen.dat.

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

int main()
{
   int grade;
   int numberOfGrades = 0;
   int totalGrades = 0;
   float averageGrade;
   ifstream inputFile;

   const int SENTINEL = -999;

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

//  read in the grades, total them, and count how many grades there are
//  stop the loop when the sentinel is read
   inputFile >> grade;
   while (grade != SENTINEL)
   {
      cout << "Grade is:  " << grade << endl;
      totalGrades = totalGrades + grade;
      numberOfGrades = numberOfGrades + 1;
      inputFile >> grade;
   }

//  calculate and print the average
   averageGrade = float(totalGrades) / numberOfGrades;
   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 gradesen.dat

97 81 88
72 90 79 85
76
83 93
-999

Sample Execution: Output

Grade is:  97
Grade is:  81
Grade is:  88
Grade is:  72
Grade is:  90
Grade is:  79
Grade is:  85
Grade is:  76
Grade is:  83
Grade is:  93
The average grade for the exam is :  84.4


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

© Copyright Emmi Schatz 2002