Michael
Michael

Reputation: 185

C++ do while loop keeps going after EOF

I have a question about file I/O.

This is my code:

#include <iostream>
#include <fstream>
#include <string>

int main(int argc, char** argv) 
{
    using namespace std;
    string InputFileName="", temp=""; //File Name entered on command line

    int Factor1=0, Factor2=0, MaxNum=0;
    if (argc < 2)
    {
        cout << "No File Name Specified\n";
        return 0;
    }
    else
    {
        //InputFileName = argv[1]; //Get File Name from command line arguments array
        ifstream inf (argv[1]); //open file for reading

        if(!inf) //check for errors opening file, print message and exit program with error
        {

            cerr << " Error opening input file\n"; 
            return 1;
        }


        do
        {
            inf >> Factor1;
            inf >> Factor2;
            inf >> MaxNum;
            cout << "Factor 1: " << Factor1 << " Factor 2: " << Factor2 << " Maximum Number: " << MaxNum << "\n";
        }while(inf);

    }
    return 0;
}

input file contains:

3 5 10
2 7 15

output is:

Factor 1: 3 Factor 2: 5 Maximum Number: 10
Factor 1: 2 Factor 2: 7 Maximum Number: 15
Factor 1: 2 Factor 2: 7 Maximum Number: 15

This is not homework. It has been 20 years since I took a C++ class. I am trying to brush up on C++. I have spent most of my career working in Visual Basic. My question is why does the while loop not catch the EOF and exit before it outputs the 3rd line and how do I fix it, or am I going about this the wrong way.

Upvotes: 0

Views: 223

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476940

You cannot predict whether I/O will succeed. You must check the return value:

while (inf >> Factor1 >> Factor2 >> MaxNum)   // checks the value of "inf", i.e.
{                                             // whether the input succeeded
    cout << "Factor 1: " << Factor1
         << " Factor 2: " << Factor2
         << " Maximum Number: " << MaxNum << "\n";
}

Your original code recklessly assumes that the input succeeded without checking, continued to consume the input, and only much later went back to ask, "oh by the way, was any of that actually legit?"

Upvotes: 3

Related Questions