【问题标题】:C++ do while loop keeps going after EOFC ++ do while循环在EOF之后继续进行
【发布时间】:2014-02-22 13:31:49
【问题描述】:

我有一个关于文件 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 循环在输出第 3 行之前没有捕获 EOF 并退出,我该如何修复它,或者我是不是走错了路。

【问题讨论】:

  • 您的缩进非常具有误导性。
  • 缩进是复制到stackoverflow编辑器的结果,我很抱歉。
  • @WilliamMichaelVondran:不过,您可以在点击“提交”之前更正它。
  • 这是一个诚实的错误,我检查过但错过了。现在已经修复了。
  • 也许它是运算符重载的诅咒,它使得教授返回值的检查变得更加困难,因为它在语法上隐藏了函数调用。也就是说,面向对象将“函数调用的成功”转移到“状态对象的有效性”,所以也许习语需要适应。

标签: c++


【解决方案1】:

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

你的原始代码鲁莽地假设输入成功而没有检查,继续使用输入,直到很久以后才回过头来问,“哦,顺便说一句,这些真的是合法的吗? "

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-10
    • 2015-07-26
    • 2018-05-09
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多