Re: how to clear ifstream failed state and move on
"cmay" <cmay@walshgroup.com> schrieb im Newsbeitrag
news:1155515575.984703.130060@b28g2000cwb.googlegroups.com...
Can someone point me in the right direction?
I am trying to loop through a file, reading some simple data.
If some bad data is read, for example "A" when a float is expected,
then I want to be able to clear the error and move on to the next
record.
It seems that calling clear does clear the error state, but it looks
like I am unable to move on to the next record. I have experimented
with .ignore with inconsistent results.
Is there a better way, or any way in fact to do this?
It is quite difficult to recover from an error when you use an input stream
to read multiple values with a single statement. The first step should be to
read only one value. Then you will at least know, which field caused the
problem.
Instead of writing something like
file >> var1 >> var2;
if (!file)
{
... handle all possible errors...
}
you should use
file >> var1;
if (!file)
{
...handle error reading var1...
}
file >> var2;
if (!file) ...
But even then it might be difficult to recover from some errors. If your
file contains "records" (lines) and each record contains multiple values,
you should better read one record at a time (as a string) and then read
values from the string. At least this will allow you to easyly skip an
ill-formed record:
std::string line;
while (std::getline(file, line))
{
std::istringstream record(line);
record >> var1 >> var2;
if (!file)
{
// ignore ill-formed record
continue;
}
...process record
}
If all the values in a single record are used to initialize a class/struct,
you should even think about using a (member) function, that takes a string
and initializes an instance of the class. You could use that function
whenever you have to initialize that data from a string, no matter where the
string comes from.
HTH
Heinz