C++循环在 EOF 之后继续运行时这样做

C++ do while loop keeps going after EOF

本文关键字:继续 运行时 这样做 之后 EOF 循环 C++      更新时间:2023-10-16

我有一个关于文件 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 Specifiedn";
        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 filen"; 
            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 循环在输出第 3 行之前没有捕获 EOF 并退出,我该如何修复它,或者我以错误的方式解决这个问题。

您无法预测 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";
}

您的原始代码鲁莽地假设输入在没有检查的情况下成功,继续使用输入,直到很久以后才回过头来问:"哦,顺便问一下,这些真的合法吗?