"Daniel Brewer" <da******@brewer.me.uk> wrote in message
news:cd***********@uns-a.ucl.ac.uk...
Hi there,
I would like to define a general operator>> function for valarrays that
allows the input of an arbitary sized array from a file. An example data
file would be like:
0 1 2 3 4 5 6
4 5 6 7 8 9 10 11 12
With each line defining a different valarray. Is it possible to do this?
Its possible but I'm not sure its a good idea because it contradicts every
other operator>> which treat newlines in the same way as every other kind of
whitespace.
I'm not saying you shouldn't write a routine to do this, I just don't think
you should call it operator>>
So far I have:
std::istream& operator>>( std::istream& is, std::valarray<double>& t )
{
for(i=0;;i++)
{
t.resize(i+1);
is >> t[i];
if (is.eof()) break;
}
return is;
}
but this does not seem to work.
Well, one reason it doesn't work is that you aren't testing for a newline
anywhere.
Any ideas what the best approach to this would be?
How about this ugly (and untested) code
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include <valarray>
#include <vector>
std::istream& read_valarray(std::istream& in, std::valarray<double>& val)
{
// read a line
std::string line;
std::getline(in, line);
// copy line to a vector
std::vector<double> temp_vec;
std::istringstream buf(line);
std::copy(std::istream_iterator<double>(buf),
std::istream_iterator<double>(buf),
std::back_inserter(temp_vec));
// copy the vector to the valarray
val.resize(temp_vec.size());
val = std::valarray<double>(&temp_vec[0], temp_vec.size());
return in;
}
john