I need to read in data files which look like this:
* SZA: 10.00
2.648 2.648 2.648 2.648 2.648 2.648 2.648 2.649 2.650 2.650
2.652 2.653 2.652 2.653
Since this is tagged as C++, the most obvious way would be using streams. Off the top of my head, something like this might do:
std::vector readFile(std::istream& is)
{
char chdummy;
is >> std::ws >> chdummy >> std::ws;
if(!is || chdummy != '*') error();
std::string strdummy;
std::getline(is,strdummy,':');
if(!is || strdummy != "SZA") error();
std::vector result;
for(;;)
{
float number;
if( !is>>number ) break;
result.push_back(number);
}
if( !is.eof() ) error();
return result;
}
Why float
, BTW? Usually, double
is much better.
Edit, since it was questioned whether returning a copy of the vector
is a good idea:
For a first solution, I'd certainly do the obvious. The function is reading a file into a vector
, and the most obvious thing for a function to do is to return its result. Whether this results in a noticeable slowdown depends on a lot of things (the size of the vector, how often the function is called and from where, the speed of the disk this reads from, whether the compiler can apply RVO). I wouldn't want to spoil the obvious solution with an optimization, but if profiling indeed shows that this is to slow, the vector should be passed in per non-const reference.
(Also note that C++1x with rvalue support, hopefully soon to be available by means of a compiler near you, will render this discussion moot, as it will prevent the vector from being copied upon returning from the function.)