On Mar 27, 9:33 am, adramo...@gmail.com wrote:
[...]
int a, b, c, d;
if (fscanf(infile, "%i%i%i%i", &a, &b, &c, &d) != 4)
fprintf(stderr, "error parsing line\n");
But using ifstream:
int a, b, c, d;
infile << a << b << c << d;
// how to check for failure...?
if ( ! infile ) ...
You can use an istream as a boolean; it will behave as true if
no error has occured, and as false once an error has been seen.
Once you've detected an error (and only then), you can use more
specific functions to determine the cause:
if ( ! infile ) {
if ( infile.bad() ) {
// Serious hardware problem... (read error, etc.)
// A lot of implementations aren't too rigorous
// about reporting this, and you might never see
// it.
} else if ( ! infile.eof() ) {
// Format error in the input stream.
} else {
// Probably an end of file (although in a few rare
// cases, infile.eof() can return true even though
// there was a format error in the input).
}
}
The error condition is sticky: it must be cleared (function
istream::clear()) before you can read further (or do anything
else) with the stream.
A typical idiom for reading files is:
while ( infile >a >b >c ) {
// ...
}
or (more often, because it allows better recovery in case of a
format error):
std::string line ;
while ( std::getline( infile, line ) ) {
std::istringstream parse( line ) ;
parse >a >b >c >d >std::ws ;
if ( ! parse || parse.peek() != EOF ) {
// Syntax error in the line...
} else {
// ...
}
}
This has the advantage of not putting the main input in an error
state, and leaving it correctly positionned for further reading
in case of an error. (Like fscanf, the >operators treat a new
line as white space. So if the input syntax is line oriented,
you probably want to use getline to read it, and istringstream
to parse each line. Something like you'd use fgets to read and
sscanf to parse in C, except that it doesn't require any special
handling for excessively long lines.)
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34