我似乎陷入了代码中某处的无限循环,但我找不到在哪里。我正在为一门课做作业,要求我平均两组学生(2 个输入文件)的分数并将结果输出到 results.out。我被困在某个地方,需要知道下一步该往哪里看。我已经复制了我的代码和下面的两个输入文件。截至目前,我的 results.out 文件中没有任何内容。
我的代码:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char courseID1; //Course Letter
char courseID2;
int count = 1,
sum = 0,
sum2 = 0,
k = 0,
score;
ifstream group1; //Input stream for group1
ifstream group2; //Input stream for group2
ofstream results; //Output stream for the results
//Open the input files
group1.open("group1.dat");
group2.open("group2.dat");
//Open the output file
results.open("results.out");
while (count <= 5)
{
//Read the class ID
group1 >> courseID1;
group2 >> courseID2;
sum = 0;
k = 0;
group1 >> score;
while(score != -999)
{
k = k + 1;
sum = sum + score;
}
float avg1 = (float)sum/k;
k = 0;
sum2 = 0;
score = 0;
group2 >> score;
while (score != -999)
{
k = k + 1;
sum = sum + score;
}
float avg2 = (float)sum2/k;
results << "CourseID\tGroup No.\tCourse Average" << endl << endl;
results << courseID1 << "\t1" << avg1;
results << "\t\t2" << avg2 << endl << endl;
count++;
}
return 0;
} //end of main
组1.dat
A 80 100 50 10 32 90 89 100 23 50 -999
B 80 90 80 94 90 34 23 63 23 80 90 -999
C 10 30 20 10 90 50 89 23 90 68 90 10 60 90 73 35 90 -999
D 34 80 45 89 90 n23 90 12 34 90 84 100 90 59 -999
E 100 83 93 20 63 -999
组2.dat
A 20 75 40 25 80 89 100 60 -999
B 80 50 70 19 10 18 80 90 90 26 -999
C 100 30 20 40 90 50 18 90 90 45 90 80 70 30 35 40 -999
D 80 85 45 92 10 90 24 90 23 65 72 90 34 100 -999
E 95 100 88 98 69 -999
以下是输出的样子:
courseID Group No. Course Average
A 1 80.50
2 82.75
B 1 78.00
2 75.35
编辑:
在将 while 循环更改为之后,我现在得到了这个结果
while( (group >> score) && score != -999)
我的 result.out 看起来像这样:
CourseID Group No. Course Average
A 162.4 20
CourseID Group No. Course Average
B 167.9091 20
CourseID Group No. Course Average
C 154.5882 20
CourseID Group No. Course Average
D 167.6 20
CourseID Group No. Course Average
D 1-NaN 20
我该如何解决?