C++成绩排序
初学C++老师安排的作业,使用C++实现成绩排序,目前实现为:从.txt文档读入学生成绩,并显示。然后选择按照哪科成绩来排序。
//main.cpp
#include"main.h"
int main()
{
ifstream in("score.txt");
if (!in)
{
cout << "Fail to open the file!" << endl;
exit(1);
}
vector<Student>s;
string line, name, id;
while (getline(in, line))
{
Student temp;
istringstream record(line);
record >> temp.Name;
record >> temp.ID;
record >> temp.Chinese;
record >> temp.Math;
record >> temp.English;
temp.Sum_all();
s.push_back(temp);
}
Disapaly_Student(s);
cout << "Which subject do you want to rank?" << endl;
string sub;
cin >> sub;
Sort_Score(s,sub);
Disapaly_Student(s);
}
//main.h
#pragma once
#include<iostream>
#include<string>
#include<vector>
#include<fstream>
#include<sstream>
using namespace std;
class Student
{
public:
string Name;
string ID;
int Chinese, Math, English,Total;
Student()
{
;
}
Student(const char &Name,const char &ID,int Chinese,int Math,int English)
{
this->Name=Name;
this->ID = ID;
this->Chinese = Chinese;
this->Math = Math;
this->English = English;
}
//Student& operator=(vector<Student> &s)
//{
// this->Name = s.;
// this->ID = ID;
// this->Chinese = Chinese;
// this->Math = Math;
// this->English = English;
// return *this;
//}
void Sum_all()
{
Total = Chinese + Math + English;
}
};
void Disapaly_Student(vector<Student>&s)
{
for (auto iter = s.begin(); iter != s.end(); iter++)
{
cout << "Name:" << iter->Name <<" "<< "ID:" << iter->ID << " "
<< "Chinese:" << iter->Chinese << " " << "Math:" <<
iter->Math << " " << "English:" << iter->English <<
" " << "Total:" << iter->Total << endl;
}
}
void Sort_Score(vector<Student>&s,string & sub)
{
Student temp;
if (sub == "Chinese")
{
for (int i = 0; i != s.size(); i++)
for (int j = 0; j != s.size() - i - 1; j++)
if (s[j].Chinese < s[j + 1].Chinese)
{
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
if (sub == "Math")
{
for (int i = 0; i != s.size(); i++)
for (int j = 0; j != s.size() - i - 1; j++)
if (s[j].Math < s[j + 1].Math)
{
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
if (sub == "English")
{
for (int i = 0; i != s.size(); i++)
for (int j = 0; j != s.size() - i - 1; j++)
if (s[j].English < s[j + 1].English)
{
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
if (sub == "Total")
{
for (int i = 0; i != s.size(); i++)
for (int j = 0; j != s.size() - i - 1; j++)
if (s[j].Total < s[j + 1].Total)
{
temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
}
该.txt文档保存选择ANSI编码,不然在cmd中,中文显示会乱码。