Sample Program: File Input - Read Until EOF

//  This program reads the cost of items purchased and adds them up.
//  The program reads from the data file cost.dat and will stop reading
//  when the end of file is reached.
//  The price of each item and the total cost are printed to the screen

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

int main()
{
   float price;
   float total = 0;
   ifstream costfile;

//  set up float output and print heading
   cout << setiosflags(ios::fixed) << setiosflags(ios::showpoint);
   cout << setprecision(2);
   cout << "Items Purchased:\n";

//  open the input file
   costfile.open("cost.dat");

//  read in the price of each item, add to the total, and print price
   costfile >> price;
   while (costfile)
   {
      total = total + price;
      cout << "    $" << price << endl;
      costfile >> price;
   }

//  print the total cost
   cout << "Total Cost:\n    $" << total << endl;
}

Sample Execution: Contents of cost.dat

9.95
11.99
5.5 1.5
14.98
6.49 2.5
3.99

Sample Execution: Output

Items Purchased:
    $9.95
    $11.99
    $5.50
    $1.50
    $14.98
    $6.49
    $2.50
    $3.99
Total Cost:
    $56.90


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

© Copyright Emmi Schatz 2002