#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;
}
文件读出并查找
#include <vector>
#include <set>
#include<iostream>
#include <string>
#include <fstream>
using namespace std;
//学号、姓名、性别和年龄
typedef struct student {
string stuNumber;
string stuName;
int stuSex;
int stuAge;
}Student;
class Solution {
private:
vector<Student> StuTable;
public:
Solution(){}
~Solution() {}
void readInfoFromFile(string fileAddr) {
ifstream readFromFile(fileAddr, ios::in);
while (!readFromFile.eof()) {
Student temp;
readFromFile >> temp.stuNumber
>> temp.stuName
>> temp.stuSex
>> temp.stuAge;
StuTable.push_back(temp);
}
}
void findStudent(string stuNum) {
bool has = false;
for (int i = 0; i < StuTable.size(); i++) {
if (StuTable[i].stuNumber == stuNum) {
showInfoOfStudent(i);
has = true;
}
}
if (!has){
cout << "The student is not in table!" << endl;
}
}
void showInfoOfStudent(int order) {
cout<<"The student info : \n"
<< StuTable[order].stuNumber <<" "
<< StuTable[order].stuName << " "
<< StuTable[order].stuSex << " "
<< StuTable[order].stuAge <<endl;
}
};
int main()
{
Solution test;
test.readInfoFromFile("d:\\Student.txt");
test.findStudent("07");
system("pause");
return 0;
}