-
File IO question
At the suggestion of some cprogramming experts, I started using filestreams rather than the old style FILE* c code.
Now I have some problems that I'm having trouble solving. This code opens a file with two columns of double data of unknown length. I want to
Code:
ifstream f( filename );
double a,p;
vector <double> v;
if(f.is_open())
{
while(!f.eof())
{
f >> a >> p;
v.push_back( a );
v.push_back( p );
}
}
else
cout << "Unable to open file";
The problem is that if my input file has a return after the last number, eof says there is still more to read, and the while loop keeps going, pushing 1 additional element onto each vector. Is testing for an identical values the only way to prevent this from happening? Does f >> a >> p raise a flag somewhere that says it didn't read a double?
Thanks for the help.
OK, well I seemed to have answered it myself:
This tests for valid input.
Well I guess I'm still wondering if there would be a way to push the value right onto the vector array without saving it in a temp variable. Something like this:
Code:
s.push( f >> double );
Is this possible?
-
You found the correct solution with if (f >> a), although you can also just move that code to the while control instead of the eof() check.
You cannot push the variable on to the vector without a temporary because of the way operator>> works. It manipulates an existing object instead of returning a new object.
If your vector started out filled with values, you could use operator[] or at() to set the data directly without the temporary, but that is not a good solution unless you know exactly how many elements will be in the input file.
-
> while(!f.eof())
Read the FAQ as to why using eof to control a loop is bad.