昨天没时间写,今天写了一个,看看行不行,我也是新手,呵呵,加油!
#include <iostream>
#include <cstring>
#include <cstdlib>
class Student {
private :
std::string Sname;
std::string Idnum;
double score;
double total_sc;
double ave;
public :
Student();
Student(const std::string name,const std::string IDnum,
double Sscore);
~Student(){}
Student Get_total_score(const Student * tmp,const int num);
friend std::ostream & operator << (std::ostream & os, const Student & t);
};
Student::Student(){
Sname = '\0';
Idnum = '\0';
score = 0.0;
total_sc = 0.0;
ave = 0.0;
}
Student::Student(const std::string name, const std::string IDnum, const double Sscore){
using std::cerr;
using std::endl;
if (Sscore < 0.0){
cerr<<"Error, Please enter a number over zero!\n"
<<"\nscore = "<<score<<endl;
}
else{
Sname = name;
Idnum = IDnum;
score = Sscore;
}
}
Student Student::Get_total_score(const Student * tmp,const int num){
Student sum;
for (int i=0; i<num; i++){
sum.total_sc += (*(tmp+i)).score;
}
sum.ave = sum.total_sc/num;
std::cout<<"Averge :"<<sum.ave<<std::endl;
return sum;
}
std::ostream & operator << (std::ostream & os, const Student & t){
os<<"Idnum :"<<t.Idnum<<"\nName :"<<t.Sname
<<"\nScore :"<<t.score<<std::endl;
return os;
}
int main()
{
using namespace std;
cout << "Enter the number of student :\n";
int stunum = 0;
while (!(cin>>stunum)){
cin.clear();
while (cin.get()!='\n'){
continue;
}
cout <<"Enter a number!"<<endl;
}
Student *pn = new Student [stunum];
string strn, stri;
double tempscore =0.0;
Student temp_score;
for (int i=0; i<stunum; i++){
cout <<"Enter Id :"<<endl;
cin.ignore();
getline (cin, stri);
cin.clear();
cout<<"Enter name :"<<endl;
cin.clear();
getline (cin, strn);
cin.clear();
cout<<"Enter score :"<<endl;
cin>>tempscore;
(*(pn+i)) = Student(strn, stri, tempscore);
}
cout<<endl;
for (int i=0; i<stunum; i++){
cout<<*(pn+i);
cout<<endl;
}
temp_score.Get_total_score(pn,stunum);
return 0;
}