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

C++, I get an infinite loop when I execute this code

本文关键字:无限循环 一个 执行 c++ 段代码 代码      更新时间:2023-10-16

我一直在试图找出问题是什么,但我不能查明它。如有任何帮助,不胜感激:

#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

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