#include <bits/stdc++.h>
#include
using namespace std;
// 玩家结构体
struct Player {
string m_id;
int m_score;
};
// 比较函数,按分数降序排序
bool cmp(Player p1, Player p2) {
return p1.m_score > p2.m_score;
}
// 添加玩家函数
void addplayer(vector& play) {
Player p;
string id;
int score;
cout << "请输入昵称:";
cin >> id;
cout << "请输入分数:";
cin >> score;
p.m_id = id;
p.m_score = score;
play.push_back(p);
}
// 显示排行榜函数
void showrank(vector& play) {
cout << "名次 " << "昵称 " << "积分 " << endl;
int i = 1;
for (vector::iterator it = play.begin(); it != play.end(); it++, i++) {
cout << " " << i << " " << it->m_id << " " << it->m_score << endl;
}
}
// 将排行榜写入文件并从文件读取数据
void textshowrank(vector& play) {
ofstream file("text02.txt");
if (file.is_open()) {
int i = 1;
file << "名次 " << "昵称 " << "积分 " << endl;
for (vector::iterator it = play.begin(); it != play.end(); it++, i++) {
file << " " << i << " " << it->m_id << " " << it->m_score << endl;
}
file.close();
} else {
cout << "文件打开失败" << endl;
return;
}
ifstream readFile("text02.txt");
if (readFile.is_open()) {
string buf;
while (getline(readFile, buf)) {
cout << buf << endl;
}
readFile.close();
} else {
cout << "文件打开失败" << endl;
return;
}
}
int main() {
vector play;
addplayer(play);
sort(play.begin(), play.end(), cmp);
showrank(play);
textshowrank(play);
return 0;
}