【问题标题】:Unable to find cause of infinite loop [closed]无法找到无限循环的原因[关闭]
【发布时间】:2013-03-30 00:57:04
【问题描述】:

我正在为一个计算学生学费的课程编写程序。我得到一个无限循环,似乎找不到原因?

代码:

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

using namespace std;

int main ()
{
    string ssn;
    char resident;
    int count = 0, hours;
    double feesOther = 30, feesTech = 18, tuition, totalFees, sumTuition = 0, subTuition;

    ofstream printFile ("StudentGrades.txt");
    if (!printFile) 
    {
        cout << " Error opening printFile" << endl;
        system ("pause");
        return 100; 
    }

    ifstream studentFile;
    studentFile.open("c:\\lab5b.dat");

    if (!studentFile)
    {
        cout << "Open error on lab5a.dat" << endl;
        system ("pause");
        return 101;
    }

    studentFile >> ssn >> resident >> hours;

    cout << "SSN          Tuition\n";
    cout << "--------------------\n";

    while (!studentFile.eof())
    {
        if (resident == 'Y' || resident == 'y')
        {
            if (hours >= 12)
                tuition = 1548;

            else

                tuition = hours * 129;
        }   
        if  (resident == 'N' || resident == 'n')
        {
            if (hours >= 12)
                tuition = 6360;

            else

                tuition = hours * 530;
        }   

        totalFees = feesOther + (hours * feesTech);

        if (totalFees > 112.50)
            totalFees = feesOther + 112.50;

        subTuition = tuition + totalFees;
        sumTuition += tuition ;
        count++;


        cout << ssn << setw(7) << showpoint << setprecision(2) << subTuition << endl;
        cout << "Total Semester Tuition: " << sumTuition << endl;

        studentFile >> ssn >> subTuition;


    }

    studentFile.close();    
    printFile.close();      

    system ("pause");
}

【问题讨论】:

  • 要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或添加打印语句)来隔离问题,方法是跟踪程序的进度,并将其与您期望发生的情况进行比较。一旦两者发生分歧,那么您就发现了您的问题。 (然后如果有必要,你应该构造一个minimal test-case。)
  • 无限循环?循环在哪里?循环的条件是什么?那个循环变体!studentFile.eof()是什么意思?

标签: c++


【解决方案1】:

您的studentfile 很可能处于失败状态,因为您从不检查读取操作是否成功。修改代码如下:

if(!(studentFile >> ssn >> resident >> hours))
{
    std::cout << "read failed";
    return 1;
}

//...    

do 
{
    // Do stuff
    // REMOVE THIS LINE: studentFile >> ssn >> subTuition;
} while (studentFile >> ssn >> subTuition); // while loop stops as soon as read fails

这里要学习的关键一课是在读写操作期间始终执行错误检查。 另外,请阅读 Why is iostream::eof inside a loop condition considered wrong?,因为 while (!studentFile.eof()) 被认为是 C++ 反模式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 2015-12-11
    • 2018-05-06
    • 2019-10-11
    • 2023-04-05
    • 1970-01-01
    • 2014-07-09
    相关资源
    最近更新 更多