Amadeus W. M. wrote:
I'm trying to read a vector from a file, while checking the correctness of
the input. I do this by setting the failbit.
double tmp;
vector<double> x;
fstream IN(argv[1], ios::in);
IN.exceptions(std::ios_base::failbit);
try{
while(IN>>tmp)
x.push_back(tmp);
}
catch(...){
}
But that's not right, because when IN reads the EOF an exception is raised.
I only want to catch the potential input errors other than the EOF.
What's the right way to do this?
Thanks.
IIRC, the failbit indicates that the *next* extraction operation on the
ifstream will fail, and if the EOF is found, the next extraction must
fail. Perhaps a more standard way to do it would be:
ifstream in( "somefile.txt" );
vector<double> v;
double d;
while( in >> d )
v.push_back( d );
//or
//
//copy( istream_iterator<double>( in ),
// istream_iterator<double>(),
// back_inserter( v ) );
if( in.bad() || !in.eof() )
{
// Some error occurred
}
If you really want to use exceptions, you catch block could look
something like:
catch( const exception& e )
{
if( in.bad() || !in.eof() )
{
// Some error occurred
}
}
Cheers! --M