0

I am new to c++ programming, first class this semester, could someone help me determine why this block of code is causing my program to hit an unexpected error and terminate when ran? This is a smaller chunk of a larger program, it at least makes it to the while loop but thats all i could figure out. Thank you in advance for any help:

void loadPresidents(bag& bagOfPresidents){
   ifstream inFile("PresidentDataBase.txt");
if(! inFile )
    cout << "File not found" << endl;
else
{
    cout << "File found!!" << endl;
    string number, name, bdDates, dtOffice, dlOffice, party, pOffice, vPresident;

    while(inFile.eof)  // while not end of file
    {
        getline(inFile, number);
        getline(inFile, name);
        getline(inFile, bdDates);
        getline(inFile, dtOffice);
        getline(inFile, dlOffice);
        getline(inFile, party);
        getline(inFile, pOffice);
        getline(inFile, vPresident);

        bagOfPresidents.add(Presidents(number, name, bdDates, dtOffice, dlOffice, party, pOffice, vPresident) );
  • `getline` might throw in the loop if you reach the end of the file inside the loop. – Mr. Anderson Dec 13 '15 at 09:34
  • In addition to the answers, there is also this problem: [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Bo Persson Dec 13 '15 at 10:11

2 Answers2

1

Code is not complete but you should use at least infile.eof() as infile.eof is a (member) function pointer and will always be non-zero (so true).

infile.eof() will call the member function and return something sensible.

marom
  • 5,064
  • 10
  • 14
1

eof names a member function (or method). You should use it as follows.

while(inFile.eof())

The way you used it (i.e. without the parentheses that mandate the function to be called) mean that you're taking the address of the function. Since that address is not zero, it will always be interpreted as a true condition.

Paulo1205
  • 918
  • 4
  • 9