istream of a dirty file

T

thomas

----------code----------
istream is(filename);

int i1,i2; string s3;
while(is>>i1>>i2>>s3){
...
}
--------code--------

The file "filename" should be formated as "int int string" for each
line,
but the last line may have only "int int" or even "int".
So the program encounter error when reading the last line.

It's supposed that I can remove the last line if it's mal-formated.
But the file is huge, opening it is time consuming.

Is there a convenient way to tell "istream" that " this line is not
formated as expected, you can stop here"?
 
L

LR

thomas said:
The file "filename" should be formated as "int int string" for each
line,
but the last line may have only "int int" or even "int".
So the program encounter error when reading the last line.

It's supposed that I can remove the last line if it's mal-formated.
But the file is huge, opening it is time consuming.

Is there a convenient way to tell "istream" that " this line is not
formated as expected, you can stop here"?

I haven't tried this snippet, but something like this might work

std::ifstream input("yourfile");
std::string line;
while(std::getline(input,line)) {
std::istringstream inline(line);
int i1, i2;
std::string s3;
if(!(inline >> i1 >> i2 >> s3)) {
// bad line
break;
}
// continue processing line
}

LR
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,191
Latest member
BuyKetoBeez

Latest Threads

Top