提问人:Alexander Chapman 提问时间:11/15/2023 最后编辑:Alexander Chapman 更新时间:11/15/2023 访问量:14
ifstream 仅读取数据 3 次
ifstream is only reading data 3 times
问:
我有一个代码,我需要计算每个性别的人数、gpa 的总和以及 gpa 的平均值。尽管男性和女性计数之间的代码几乎相同,但它没有从第二个循环的文件中读取任何信息。
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
void openFiles(ifstream& read, ofstream& write)
{
read.open("StudentsPreformanceData.txt");
if (read.is_open())
cout << "File Opened" << endl;
else
cout << "Error try again";
write.open("Results.txt");
write << fixed << showpoint << setprecision(2);
}
void initialize(int& countFemale, int& countMale, double& sumFemale, double& sumMale)
{
countFemale = 0;
countMale = 0;
sumFemale = 0.00;
sumMale = 0.00;
}
void sumGrades(ifstream& read, double& sum, char gender)
{
char student;
double grade;
while (!read.eof())
{
read >> student;
read >> grade;
if (student == gender)
sum = sum + grade;
//cout << student << " " << grade << " " << sum << endl;
}
read.close();
}
double averageGrades(ifstream& read, double sum, int& count, char gender)
{
char student;
double grade;
while (!read.eof())
{
read >> student;
read >> grade;
if (student == gender)
{
count = count + 1;
}
cout << student << " " << count << " " << sum << endl;
}
return sum / count;
read.close();
}
void printResults()
{
}
int main()
{
ifstream read;
ofstream write;
openFiles(read, write);
int countFemale, countMale;
double sumFemale, sumMale;
initialize(countFemale, countMale, sumFemale, sumMale);
cout << countFemale << sumFemale << countMale << sumMale << endl;
sumGrades(read, sumFemale, 'f');
cout << countFemale << " " << sumFemale << " " << countMale << " " << sumMale << endl;
openFiles(read, write);
sumGrades(read, sumMale, 'm');
cout << countFemale << " " << sumFemale << " " << countMale << " " << sumMale << endl;
openFiles(read, write);
averageGrades(read, sumMale, countMale, 'm');
cout << countFemale << " " << sumFemale << " " << countMale << " " << sumMale << endl;
openFiles(read, write);
averageGrades(read, sumFemale, countFemale, 'f');
cout << countFemale << " " << sumFemale << " " << countMale << " " << sumMale << endl;
}
我很困惑,因为我尝试交换男性和女性的位置,再一次,第二名不算数。代码打印出打开的文件,所以我知道它正在打开,我只是不知道为什么它不会在代码中的那个时候第四次运行列表。
答: 暂无答案
评论