Proper error checking is pretty easy, and short. The only error check
possibly missing in
lastchance’s example was verifying that the number of elements obtained matched the give value. I suggest a single modification:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
#include <fstream>
#include <valarray>
#include <string>
using namespace std;
valarray<double> readFile( const string &filename )
{
ifstream in( filename );
int npts;
in >> npts;
valarray<double> V( npts );
for ( double &e : V ) in >> e;
return in ? V : valarray<double>{}; // all or nothing, baby
}
int main()
{
valarray<double> V = readFile( "f1.txt" );
cout << "Points: " << V.size() << '\n'
<< "Minimum: " << V.min() << '\n'
<< "Maximum: " << V.max() << '\n'
<< "Average: " << V.sum() / V.size() << '\n';
}
| |
Notice how we are NOT checking for EOF — that may be incorrect:
• it is correct to check EOF if we know that the data is always
the only content in the file AND
we do something to find it
• it is not correct if the data may be followed by any other data
(of any kind, which wouldn't be read anyway)
We don’t know which to choose.
lastchance’s code (correctly, IMHO) simply assumed the data had no error in format, which is something that is a fairly normal characteristic of scientific computing.
As it is, there is potential for another error: too little data in a file with additional data following. The current code cannot detect that. (Nor should it, because again, the “N a1 a2 ... aN” format is
very standard.)
[edit] Note also that my suggested modification
throws away data if something is wrong. This may not be desired.