C ++,当我执行这段代码时,我得到一个无限循环

时间:2014-08-17 23:39:59

标签: c++ infinite-loop

我一直试图找出问题所在,但我无法确定它。任何帮助将不胜感激:

#include<iostream>
#include<fstream>

#define infile "Input.txt"

using namespace std;


void readFromFile(int numOfPeopleAndSalary[6][2], int departmentID[50][6], int &counter, int &totalSalary)
{
    int id, depNum, salary, peopleNum;
    counter = 0;

    ifstream myfile;
    myfile.open(infile);

    if (myfile.fail())
    {
        cout << "Did not read the file, there is a problem" << endl;
        system("pause");
    }
    else
    {


        while (!myfile.eof())
        {
            myfile >> id >> depNum >> salary;


            numOfPeopleAndSalary[depNum][0] = numOfPeopleAndSalary[depNum][0] + 1;
            numOfPeopleAndSalary[depNum][1] = numOfPeopleAndSalary[depNum][1] + salary;

            peopleNum = numOfPeopleAndSalary[depNum][0];

            departmentID[peopleNum][depNum] = id;

            totalSalary = totalSalary + salary;

            counter++;
        }
    }
}

int averageFunction(int counter, int totalSalary, int numOfPeopleAndSalary[6][2], int departmentID[50][6], int secondAverage[6])
{
    int average;

    if (counter == 0)
    {
        average = 0;
    }
    else
    {
        average = totalSalary / counter;
    }

    for (int i = 1; i < 6; i++)
    {
        if (numOfPeopleAndSalary[i][0] == 0)
        {
            secondAverage[i] = 0;
        }
        else
        {
            secondAverage[i] = numOfPeopleAndSalary[i][1] / numOfPeopleAndSalary[i][0];
        }
    }

    return average;
}

int main()
{
    int counter, average, numberOfPeeps;
    int numOfPeopleAndSalary[6][2] = {0,0,0,0,0,0,0,0,0,0,0,0};
    int departmentID[50][6];
    int secondAverage[6];
    int totalSalary = 0;

    readFromFile(numOfPeopleAndSalary, departmentID, counter, totalSalary);

    average = averageFunction(counter, totalSalary, numOfPeopleAndSalary, departmentID, secondAverage);

    for (int i = 1; i < 6; i++)
    {
        cout << "Department #: " << i << " Number of people: " << numOfPeopleAndSalary[i][0]
            << " Total Salary: " << numOfPeopleAndSalary[i][1] << endl;
        cout << secondAverage[i] << endl;

        numberOfPeeps = numOfPeopleAndSalary[i][0] + 1;

        cout << "----------Employee ID's---------" << endl;
        for (int j = 1; j < numberOfPeeps; i++)
        {
            cout << departmentID[j][i] << endl;
        }

    }

    system("pause");
    return 0;
}

当我运行它时,它应该只读取外部文件(Input.txt)中的信息并进行所有计算。在外部文件中我有这些测试用例:

23 1 66
6 3 54
213 5 54
434 4 24
324 4 32
789 2 32
4 2 24
345 3 32
568 5 12
24 1 67
789 3 54
24 5 56
56 2 43
9 3 45
32 4 53
67 4 75

如果您愿意,可以复制和过去。

1 个答案:

答案 0 :(得分:4)

i++替换为j++

中的for (int j = 1; j < numberOfPeeps; i++)