|
|
|
|
|
|
|
int main()
{
float amt1; // Number of gallons for fillup 1
float amt2; // Number of gallons for fillup 2
float amt3; // Number of gallons for fillup 3
float amt4; // Number of gallons for fillup 4
float startMiles; // Starting mileage
float endMiles; // Ending mileage
float mpg; // Computed miles per gallon
ifstream inMPG; // Holds gallon amounts and mileages
ofstream outMPG; // Holds miles per gallon output
// Open the files
inMPG.open(inmpg.dat);
outMPG.open(outmpg.dat);
// Get data
inMPG >> amt1 >> amt2 >> amt3 >> amt4
>>startMiles >> endMiles;
// Compute miles per gallon
mpg = (endMiles - startMiles) / (amt1 + amt2 + amt3 + amt4);
// Output results
outMPG << For the gallon amounts << endl;
outMPG << amt1 < << amt2 <<
<< amt3 << << amt4 << endl;
outMPG << and a starting mileage of << startMiles << endl;
outMPG << and an ending mileage of << endMiles << endl;
outMPG << the mileage per gallon is << mpg << endl;
return 0;
} |
|
|
|
|
|
|
|
|
In this program, what happens if you mistakenly specify cout instead of outMPG in one of the output statements? Nothing disastrous; the output of that one statement merely goes to the screen instead of the output file. And what if, by mistake, you specify cin instead of inMPG in the input statement? The consequences are not as pleasant. When you run the program, the computer will appear to go dead (to hang). Here's the reason. |
|
|
|
|
|
|
|
|
Execution reaches the input statement and the computer waits for you to enter the data from the keyboard. But you don't know that the computer is waiting. There's no message on the screen prompting you for input, and you are assuming (wrongly) that the program is getting its input from a data file. So the computer waits, and you wait, and the computer waits, and you wait. Every programmer at one time or another has had the experience of thinking |
|
|
|
|
|