Please send questions to
st10@humboldt.edu .
#include <fstream>
using namespace std;
// Contract: char[] double[] int& -> bool
// Purpose: try to open the file named fname for reading,
// which is expected to contain an integer
// number of rats' weights, followed by that
// many rats' weights expressed as doubles.
// Initialize ratWts to be an array of that
// many rats' weights, store those rats' weights
// into it, and change the argument corresponding
// to numWts to contain the number of rats'
// weights.
//
// Returns false if cannot open fname for reading;
// returns true if it can.
//
// Examples: if a file in the current directory named
// ratWeights.txt contains the following:
// 4
// 13.3
// 5
// 27.1
// 15.5
// ...then
// wtsIntoArray("ratWeights.txt", allWts, howMany)
// == true,
// and howMany should be set to 4,
// and allWts[0] == 13.3
// allWts[1] == 5
// allWts[2] == 27.1
// allWts[3] == 15.5
//
// by: Sharon M. Tuttle
// last modified: 10-29-03
bool wtsIntoArray(const char fname[],
double ratWts[], int& numWts)
{
// local variables
ifstream input_stream;
// can you open specified file for reading?
input_stream.open(fname);
if (input_stream.fail())
{
// this is not a main function! So, exit(1) not
// appropriate.
// returning a value of false IS appropriate, tho
return false;
}
// IF reach here --- we DID successfully open the
// file.
// how many rats' weights are there?
input_stream >> numWts;
// ...and now try to FILL ratWts with that many
// weights...
for (int i=0; i < numWts; i++)
{
input_stream >> ratWts[i];
}
// if get here --- clean up and return true
input_stream.close();
return true;
}