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 that for io1.cpp?
// What is the SAME?
// Contract: void -> int
// Purpose: interactively find out how many rats there
// are, get their weights, and determine the total
// of all of their weights. Print this total weight
// in a message to the file "allRatWeights.txt" in
// the directory from where this program is run.
//
// Examples: if, when prompted, the user enters 4,
// then the user should be prompted to enter
// 4 rat weights; if the 4 weights entered
// are 13.3, 5, 27.1, and 15.5, then it
// should print to the file "allRatWeights.txt"
// in the current directory:
// The total weight is 60.9
//
// by: Sharon M. Tuttle
// last modified: 10-28-03
int main ( )
{
// local declarations
double weight, total = 0;
int num_rats;
// we declare an ofstream variable, an output file
// stream variable, giving it the name output_stream
ofstream output_stream;
// an output file stream needs to be OPENED in
// order to write to it --- this open function
// expects a single string parameter, representing
// the name of the file where you want the output
// to go
// (why open it so soon? because why get the info
// from the user, if will not be able to write
// to output file?)
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
// output file;
// how many rats are there?
cout << "how many rats are being entered? ";
cin >> num_rats;
// get each rat's weight, accumulate sum of weights
for (int i=0; i < num_rats; i++)
{
cout << "Enter the next rat weight: ";
cin >> 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...)
// (look how I can call an OS system call from
// C++ --- BUT THIS IS NOW
// UNIX/LINUX/OS X-DEPENDENT!!)
output_stream << system("date") << endl;
output_stream << "The total weight is " << total
<< endl;
// then, when you are done with it, you should
// close your output file stream...
output_stream.close();
return 0;
}