Please send questions to
st10@humboldt.edu .
#include <fstream> // DOES fstream include iostream? NO;
#include <iostream> // (comment this out, to see this!)
#include <cstdlib> // (so can use exit function)
using namespace std;
// consider: what is DIFFERENT between this opening
// comment block, and those for io1.cpp, io2.cpp,
// io4.cpp?
// What is the SAME?
// Contract: void -> int
// Purpose: read the number of rats and their weights
// from file "ratWeights.txt" in the current
// working directory, sum their weights,
// and print a message to the file
// "allRatsWeight.txt" in the current directory
// including their total weight.
//
// IMPORTANT ASSUMPTIONS: it assumes that ratWeights.txt
// already exists in the current directory, and that
// it contains a number of rats, followed by precisely
// that many rats' weights (as type double). These
// values must be separated by some kind of white
// space.
//
// Examples: if, when started, the file ratWeights.txt
// contains:
// 4
// 13.3
// 5
// 27.1
// 15.5
// ...then io5 should print to file
// allRatWeights.txt (in the current directory)
// the message:
// The total weight is 60.9
//
// by: Sharon M. Tuttle
// last modified: 10-28-03
int main()
{
// declaration section
float weight, total = 0;
int num_rats;
// we declare an ifstream variable, an input
// file stream variable, giving it the name
// input_stream
ifstream input_stream;
// we declare an ofstream variable, an output file
// stream variable, giving it the name output_stream
ofstream output_stream;
// open the input and output streams using their
// respective open functions
input_stream.open("ratWeights.txt");
if (input_stream.fail())
{
cout << "Could not open ratWeights.txt for input..."
<< endl;
exit(1);
}
output_stream.open("allRatWeights.txt");
if (output_stream.fail())
{
cout << "Could not open allRatWeights.txt for"
<< " output..." << endl;
exit(1);
}
// if REACH here --- then successfully opened
// BOTH input file and output file;
// how many rats are there? I read it from the
// FILE, using the input file stream, instead of
// from cin
//
// note how I do *NOT* use a prompt, here...
input_stream >> num_rats;
// get each rat's weight, accumulate sum of weights
for (int i=0; i < num_rats; i++)
{
// read in each rat's weight from input file
// stream instead of cin --- again, NO prompt
// is necessary;
input_stream >> weight;
total += weight;
}
// report the sum of all the rats' weights, but to
// the output file stream instead of to
// cout! (Notice how, once you set it up, you treat
// it like cout...)
output_stream << "The total weight is " << total
<< endl;
// then, when you are done with it, you should
// input and output file streams...
input_stream.close();
output_stream.close();
return 0;
}