-5

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

代码:

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

1 回答 1

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

这里要学习的关键一课是在读写操作期间始终执行错误检查。另外,请阅读为什么循环条件内的 iostream::eof 被认为是错误的?aswhile (!studentFile.eof())被认为是 C++ 反模式。

于 2013-03-30T01:05:14.277 回答