我的任务是从毕业簿文本文件中读取每个学生的课程、期中和期末成绩以及学生 ID 和姓名的平均值。到目前为止,代码能够适当地编译和计算分数,但它不会读取学生 ID 和名字和姓氏。
我很确定原因是 main() 中的 currentStudent 变量没有任何参数并使构造函数使用默认值。但我不确定如何在 main() 中从 Student 类中给出 currentStudent 值。我最好的解决方案是将所有内容从 ReadData 移到 main() 中,但从我的作业中对 ReadData 的描述来看,我认为我在那里拥有我需要的一切:
“一种名为 ReadData(istream&) 的方法,它读取学生的数据。它按顺序读取 ID 号(整数)、名字和姓氏(字符串)、10 个程序分数(所有整数)以及期中和考试分数(也整数)。如果所有数据都读取成功,则返回 true,否则返回 false"
对于冗长的描述,我很抱歉,我只是看看我是否能有效地解释我的情况。任何帮助或建议将不胜感激。
我只在下面包含了类定义、构造函数、ReadData 和 main,因为其他所有内容都只是方程式和 get/sets,我很确定它们都可以工作,而且我试图减少你们可爱的人必须阅读的内容通过。如果有人想查看完整的代码,我会发布其余的。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Student
{
private:
int studentID;
string firstName,
lastName;
int score[ 10 ];
int midterm, final;
public:
Student ( int, string, string );
bool ReadData ( istream& );
//fstream WriteData ( ostream& ); // I need to clear up with professor first
void setStudentID ( int );
void setFirstName ( string );
void setLastName ( string );
void setMidterm ( int );
void setFinal (int );
const int getStudentID ( );
const string getFirstName ( );
const string getLastName ( );
const int getMidterm ( );
const int getFinal ( );
void setProgramScore ( int, int[ ] );
int getProgramScore ( int );
const double ProgramAvg( );
const double CourseAvg( );
~Student( );
};
Student::Student ( int id = 0, string f = "", string l = "" )
{
setStudentID ( id );
setFirstName ( f );
setLastName ( l );
};
bool Student::ReadData( istream &readStudent )
{
int id;
string first, last;
int x[ 10 ], mid, fin;
readStudent >> id >> first >> last;
for ( int i = 0; i <= 10 - 1; i++ )
{
readStudent >> x [ i ];
setProgramScore( i, x );
}
readStudent >> mid >> fin;
Student studentInfo ( id, first, last );
setMidterm( mid );
setFinal( fin );
if ( readStudent.good( ) )
return true;
else
return false;
};
// getter、setter 和中间的计算
int main( )
{
ifstream readStudent;
int lineCount = 0;
double totalProgramAvg = 0
, totalFinalAvg = 0
, totalCourseAvg = 0;
Student currentStudent;
readStudent.open ( "gradebook.txt" );
if ( readStudent.is_open ( ) )
{
while ( currentStudent.ReadData ( readStudent ) == true )
{
totalProgramAvg += currentStudent.ProgramAvg();
totalFinalAvg += currentStudent.getFinal();
totalCourseAvg += currentStudent.CourseAvg();
cout << currentStudent.getStudentID() << " "
<< currentStudent.getFirstName() << " "
<< currentStudent.getLastName() << " ";
for ( int j = 0; j < 10; j++ )
cout << currentStudent.getProgramScore( j ) << " ";
cout << currentStudent.getMidterm() << " "
<< currentStudent.getFinal() << endl;
cout << totalProgramAvg << " " << totalCourseAvg << endl;
lineCount++;
};
readStudent.close( );
cout << lineCount << endl << totalProgramAvg / lineCount << "\n" << totalFinalAvg / lineCount << "\n" << totalCourseAvg / lineCount;
system ("pause");
};
};