|
|
|
|
|
|
|
Figure 4-3
The Effect of Opening a File |
|
|
|
|
|
|
|
|
inMPG >> amt1 >> amt2 >> amt3 >> amt4 >> startMiles >> endMiles; |
|
|
|
|
|
|
|
|
to instruct the computer to read data from the file inMPG instead of from cin. And all of the output statements that write to the file outMPG would specify outMPG, not cout, as the destination: |
|
|
|
|
|
|
|
|
outMPG << the mileage per gallon is << mpg << end1; |
|
|
|
|
|
|
|
|
What is nice about C++stream I/O is that we have a uniform syntax for performing I/O operations, regardless of whether we're working with the keyboard and screen, with files, or with other I/O devices. |
|
|
|
|
|
|
|
|
An Example Program Using Files |
|
|
|
|
|
|
|
|
Here's the Mileage program reworked. Now it reads its input from the file inMPG and writes its output to the file outMPG. Compare this program with the original version on page 83 and notice that the constants have disappeared because the data is now input at execution time. |
|
|
|
|
|
|
|
|
//*************************************************************
// Mileage program
// This program computes miles per gallon given four amounts
// for gallons used, and starting and ending mileage
//*************************************************************
#include <iostream.h>
#include <fstream.h> // For file I/O
|
|
|
|
|
|