无法找到无限循环的原因

时间:2013-03-30 00:57:04

标签: c++

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

代码:

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

1 个答案:

答案 0 :(得分: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 ++反模式。