Please send questions to
st10@humboldt.edu .
/*--------------------------------------------------
created by smtuttle at Tue May 4 17:54:07 PDT 2010
--------------------------------------------------*/
#include <fstream> // includes iostream
#include <cmath>
using namespace std;
/*--------------------------------------------------
Contract: sum_from_file : string -> double
Purpose: expects the name of a file in the current working directory,
expected to contain on its first line the number of values
in that file, followed by that many double values, one per line;
it then returns the sum of those values.
Examples: if file april_wts.txt contains:
5
10.3
17.7
4
200.4
58.66
then:
sum_from_file("april_wts.txt") == 291.06
--------------------------------------------------*/
double sum_from_file(string input_file)
{
ifstream input_stream;
double sum_so_far = 0.0;
double latest_value;
int num_values;
// find out how many values there are
// (note: the open method needs an old-style char* string!
// calling the c_str method on a new-style string
// returns that string in char* type...)
input_stream.open(input_file.c_str());
input_stream >> num_values;
// read in and sum that many values
for (int i=0; i < num_values; i++)
{
input_stream >> latest_value;
sum_so_far += latest_value;
}
return sum_so_far;
}