无法找到无限循环的原因 [英] Unable to find cause of infinite loop

查看:111
本文介绍了无法找到无限循环的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a program for a class that computes tuition for students. I am getting an infinite loop and cant seem to find why?

代码:

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


推荐答案

> studentfile 很可能处于失败状态,因为您永远不会检查读取操作是否成功。按如下所示更改代码:

Your studentfile is most likely in a fail state, as you never check whether the read operations are successful or not. Change the code as follows:

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

这里学习的关键教训是 always在读取和写入操作期间执行错误检查
另外,请阅读为什么是iostream :: eof在一个循环条件被认为是错误? as while(!studentFile.eof())被认为是一个C ++反模式。

The key lesson to learn here is always perform error checking during read and write operations. Also, please read Why is iostream::eof inside a loop condition considered wrong? as while (!studentFile.eof()) is considered a C++ anti-pattern.

这篇关于无法找到无限循环的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆