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?
// What is the SAME?
// Contract: void -> int
// Purpose: ask the user for the name of a file containing
// the number of rats and their weights
// in the current working directory, sum their
// weights,
// and print a message to the screen giving
// their total weight.
//
// IMPORTANT ASSUMPTIONS: it assumes that
// the file name given by the user
// 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 io7 should print to the screen the
// message:
// The total weight is 60.9
//
// by: Sharon M. Tuttle
// last modified: 11-7-03
int main ( )
{
// local declarations
float weight, total = 0;
int num_rats;
char fileName[25];
// we declare an ifstream variable, an input
// file stream variable, giving it the name
// input_stream
ifstream input_stream;
// an input file stream needs to be OPENED in
// order to read from it --- this open function
// expects a single string parameter, representing
// the name of the file from which you want to read
//
// PLEASE note an IMPORTANT assumption here: the
// file has ALREADY been filled with data in
// some way, at this point;
cout << "What file contains the rat weights? ";
cin >> fileName;
input_stream.open(fileName);
if (input_stream.fail())
{
cout << "Could not open " << fileName
<< " for input..."
<< endl;
exit(1);
}
// if REACH here --- then successfully opened
// input 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 to the screen
cout << "The total weight is " << total << endl;
// then, when you are done with it, you should
// close your input file stream...
input_stream.close();
return 0;
}