1. 程式人生 > >第十五週(專案二)——用檔案儲存學生的名單。

第十五週(專案二)——用檔案儲存學生的名單。

/*煙臺大學計算機學院學生
*All right reserved.
*檔名稱:用檔案儲存學生的名單
*作者:王洪海
*完成日期:2014年6月5日
*版本號:v1.0
*對任務及求解方法的描述部分:用檔案儲存學生的名單
*我的程式:*/

#include <iostream>
#include <fstream>
#include <string>
#include<cstdlib>
using namespace std;

class Student
{
  public:
   double get_total();    // 求單個學生總分
   int get_stu_num();  // 等到學生的數量
   double get_total_sum();  // 所有學生總分和
   bool pass(double );
   friend istream &operator >>(istream &in,Student &s);
   friend ostream &operator <<(ostream &out,Student &s);
  private:
   string name;
   double cpp;
   double math;
   double english;
   double total;
   static int stu_num;   //學生人數,處理為類的靜態靜態成員合適
   static double total_sum;  //學生總分和
};
double Student::total_sum=0;
double Student::get_total()
{
    total=cpp+math+english;
    return total;
}

int Student::stu_num=0;
int Student::get_stu_num()
{
    return stu_num;
}

double Student::get_total_sum()
{
    return total_sum;
}

bool Student::pass(double avg)
{
    if(total>=avg&&(cpp>=60)&&(math>=60)&&(english>=60))
      return true;
    else
      return false;
}

istream &operator >>(istream &in,Student &s)
{
   in>>s.name>>s.cpp>>s.math>>s.english;
   s.total=s.cpp+s.math+s.english;
   Student::stu_num++;     //在讀入資料過程中,用靜態成員記錄下來具體的學生人數和總分和
   Student::total_sum+=s.total;
   return in;
}

ostream &operator <<(ostream &out,Student &s)
{
    out<<s.name<<"\t";
    out<<s.cpp<<"\t";
    out<<s.math<<"\t";
    out<<s.english<<"\t";
    out<<s.get_total()<<"\t";
    return out;
}
int main()
{
    Student stud[200],t;
    double total_avg=0;
    int i=0;
    //string sname;
    ifstream infile("score.txt",ios::in);
    if(!infile)
    {
       cerr<<"date error!";
       exit(0);
    }
    while(infile>>stud[i])
    {
        i++;
    }
    infile.close();

    for(i=0;i<t.get_stu_num();i++)
    {
        double s=0;
        s+=stud[i].get_total();
        total_avg=s/t.get_stu_num();
    }
    ofstream outfile("pass_score.txt",ios::out);
    if(!outfile)
        {
            cerr<<"open error!"<<endl;
            exit(0);
        }
    for(i=0;i<t.get_stu_num();i++)
    {
        if(stud[i].pass(total_avg))
         outfile<<stud[i]<<endl;
    }
    outfile.close();
    cout<<"請到 pass_score 檔案中檢查。"<<endl;
    return 0;
}

執行結果,如下圖:

執行前檔案:


執行後文件: