欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

文件读写和成绩排序

程序员文章站 2022-03-15 19:25:21
...
#include <iostream>
#include <vector>
#include <cmath>
#include<fstream>
#include <string>
#include<algorithm>

using namespace std;

typedef struct stu {
	string name;
	int age;
	double score;
	stu(){}
	stu(string sname,int sage,double sscore):name(sname),age(sage),score(sscore){}
}Student;

bool cmpBigger(const Student& stu1, const Student& stu2) {
	return stu1.score > stu2.score;
}




class Solution
{
private:
	vector<Student> m_StudentTable;
public:
	Solution() {}
	~Solution() {}

	void readFromConsole(){
		string stuName = "";
		int age = 0;
		double score = 0.0;

		for (int i = 0; i < 4; i++) {
			cin >> stuName >> age >> score;
			m_StudentTable.push_back(stu(stuName, age, score));
		}
	}

	void writeToFile(const string& fileAddress) {
		ofstream outputToFile(fileAddress, ios::out);
		for (Student stu : m_StudentTable) {
			outputToFile << stu.name << " " << stu.age << " " << stu.score << endl;
		}
		outputToFile.close();
	}

	void readFromFile(const string& fileAddress) {
		m_StudentTable.clear();
		Student stu;

		ifstream inputFromFile(fileAddress, ios::in);
		for (int i = 0; i < 4; i++) {
			inputFromFile >> stu.name >> stu.age >> stu.score;
			m_StudentTable.push_back(stu);
		}
		
		inputFromFile.close();
	}

	void sortByScoresUp() {
		sort(m_StudentTable.begin(), m_StudentTable.end(),cmpBigger);
	}

	void showHighestScoreStudent() {
		Student HighestScoreStudent = m_StudentTable.at(0);
		cout << "成绩最高的学生信息: "<<HighestScoreStudent.name << " " << HighestScoreStudent.age
			<< " " << HighestScoreStudent.score << endl;
	}

};


int main()
{
	Solution test;
	string file("d:\\Student.txt");
	test.readFromConsole();
	test.writeToFile(file);
	test.readFromFile(file);
	test.sortByScoresUp();
	test.showHighestScoreStudent();
	system("pause");
	return 0;
}

相关标签: 算法的乐趣