0

Hi i currently wrote a program but I'm having problems with reading the file. It seems to have read the last line twice, as a result, producing the same results twice.

I had put the getline() function to read the first line, in order to store the string for the variable G. The rest, I had stored it in a vector of the class object.

basically the file is opened and it performs this loop

file.open("bodies1.txt");
getline(file, G1);
....


while(!file.eof)
{
  file >> body;
  bodies.push_back(body);
}

this is what the text file look like (this is just a sample. not the actual thing)

0.02932
Sun 32 42 53 2 2
Moon 49 32 4 2 1
Jupiter 32 53 2 3 2

I really was wondering why it read the last line twice. Any suggestions?

  • 1
    @JesseGood I agree that the EOF is the problem, I'm not sure that this question is a duplicate of that question however. That answer will solve their problem. – AlexLordThorsen Apr 30 '13 at 20:23
  • @Rawrgulmuffins: Problems related to the C++ anti-pattern `while(!file.eof)` are very common. Check out how many duplicates are linked to that question. – Jesse Good Apr 30 '13 at 20:34

1 Answers1

1
while(!file.eof())
{
  file >> body;
  bodies.push_back(body);
}

After reading the last object in to body, eof is the next character. Then

file >> body;

tries to read it and fails. So whatever was in body before is still there and will be pushed in to the vector.


instead you should read like

while(file >> body)
{
  bodies.push_back(body);
}

This way your while stops as soon as you encounter eof() and you will not do an extra push in to the vector.

stardust
  • 5,628
  • 1
  • 17
  • 20