zabusz
zabusz

Reputation: 38

ifstream identifying end of file

I have a file containing data in the following format:

name1 p1 p2 ... p11
name2 p1 p2 ... p11
...

(parameters are not necessarily in one line)

My goal is to read the name and the 11 parameters, do something with them, then do the same with the next block of data until there is no more. The code below does this just fine, but after reaching the end of file, it does one more run that reads garbage. Can anyone help me to fix this?

std::ifstream file("data.txt");
std::string name;
double p[11];

while(file.peek() != EOF){
    file >> name 
         >> p[0] >> p[1] >> p[2] >> p[3]
         >> p[4] >> p[5] >> p[6] >> p[7]
         >> p[8] >> p[9] >> p[10];
/* 
    doing something with the data
*/
}
file.close();

Upvotes: 1

Views: 273

Answers (1)

user0042
user0042

Reputation: 8018

The usual way to do that in c++ is to check the stream state after doing the extraction:

while(file >> name 
           >> p[0] >> p[1] >> p[2] >> p[3]
           >> p[4] >> p[5] >> p[6] >> p[7]
           >> p[8] >> p[9] >> p[10]) {
/* 
    doing something with the data
*/
}

If there's no more data or an error in the input the loop will stop.

Here is some more information how and why this works:

std::basic_ios::operator bool

Upvotes: 1

Related Questions