1

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();
zabusz
  • 13
  • 3
  • Offchance, but maybe you have an extra line at the end of the file? A blank one? – Rivasa Sep 03 '17 at 13:45
  • 1
    What you do is no better than `while (!file.eof())` [and that is almost always wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – Some programmer dude Sep 03 '17 at 13:48
  • I already checked it, there is no whitespace or line after the last number – zabusz Sep 03 '17 at 13:52

1 Answers1

1

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

user0042
  • 7,691
  • 3
  • 20
  • 37