while (file.eof()) causes repeat of last input

#include <iostream>

#include <fstream>

using namespace std;

int main ()

{

ifstream inFile;

ofstream outFile;

inFile.open("inGrades.txt");

if(!inFile)

{

cout<< "Unable to open input file.\n";

exit(1); //terminate with error

}

outFile.open("outGrades.txt");

if(!outFile)

{

cout<< "Unable to open input file.\n";

exit(1); //terminate with error

}

char lastName[15], firstName[15];

int Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10;

double average;

char next;

while (!inFile.eof())

{ inFile.get(next);

outFile.put(next);

inFile >>lastName >>firstName;

inFile >>Q1>>Q2>>Q3>>Q4>>Q5>>Q6>>Q7>>Q8>>Q9>>Q10;

average = ((Q1 + Q2 + Q3 + Q4 + Q5 + Q6 + Q7 + Q8 + Q9 + Q10)/10);

outFile <<lastName<<" "<<firstName<<" "<<Q1<<" "<<Q2<<" "<<Q3<<" "<<Q4<<" "

<<Q5<<" "<<Q6<<" "<<Q7<<" "<<Q8<<" "<<Q9<<" "<<Q10<<" "<< average <<endl;

}

inFile.close();

outFile.close();

return 0;

}

inGrades.txt

Mel Gibson 100 87 89 95 91 94 93 90 98 100

Harper Heather 100 87 97 90 100 93 91 99 87 85

Stanton Cecilia 95 93 87 100 89 92 80 85 91 92

outGrade.txt

Mel Gibson 100 87 89 95 91 94 93 90 98 100

Harper Heather 100 87 97 90 100 93 91 99 87 85

Stanton Cecilia 95 93 87 100 89 92 80 85 91 92
95 93 87 100 89 92 80 85 91 92



Answer this question

while (file.eof()) causes repeat of last input

  • karcheee

    Is this C# or C++ If it's C# is there any particular reason you've chosen not to use a StreamReader
  • Darren Wang

    sorry guys, the problem is the infile has a hard return
  • gdanielg

    thank you for the tip, however it is still doing it.

    inFile.get(next);

    while (!inFile.eof())

    {

    outFile.put(next);

    inFile >>lastName >>firstName;

    inFile >>Q1>>Q2>>Q3>>Q4>>Q5>>Q6>>Q7>>Q8>>Q9>>Q10;

    average = ((Q1 + Q2 + Q3 + Q4 + Q5 + Q6 + Q7 + Q8 + Q9 + Q10)/10);

    outFile <<lastName<<" "<<firstName<<" "<<Q1<<" "<<Q2<<" "<<Q3<<" "<<Q4<<" "

    <<Q5<<" "<<Q6<<" "<<Q7<<" "<<Q8<<" "<<Q9<<" "<<Q10<<" "<< average <<endl;

    inFile.get(next);

    }

    inFile.close();

    outFile.close();

    any other suggestion would be helpful, it looks like it should work but....


  • Lord_of_The_Rings

    C++
  • urbansound

    There is no way that this could be C#. It's C++.

    while (!inFile.eof())

    { inFile.get(next);

    outFile.put(next);

    eof is set when a read operation fails. You should call get before the loop, and again at the bottom of the loop, so that the eof is called after the operation that sets it, but before you write anything.



  • while (file.eof()) causes repeat of last input