C ++ do while循环继续在EOF之后

时间:2014-02-22 13:31:49

标签: c++

我对文件I / O有疑问。

这是我的代码:

#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;
}

输入文件包含:

3 5 10
2 7 15

输出是:

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

这不是作业。我参加C ++课程已有20年了。我试图了解C ++。我的大部分职业生涯都是在Visual Basic中工作的。我的问题是为什么while循环没有捕获EOF并在它输出第3行之前退出,我该如何解决它,或者我是以错误的方式解决这个问题。

1 个答案:

答案 0 :(得分:3)

无法预测I / O是否会成功。您必须检查返回值:

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";
}

你的原始代码鲁莽地认为输入成功而没有检查,继续消费输入,并且很久以后又回去问,“哦,顺便说一句,这是否真的合法? “