每次输入都要从文件中先加载数据到数组中,然后再把更新的数据添加进数组中,最后再写入文件 。
代码中文件路径填自己电脑的路径
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<algorithm>
#include<sstream>
using namespace std;
struct Player
{
string name;
int score;
};
bool cmp(const Player& player1, const Player& player2)
{
return player1.score > player2.score;
}
void updateRankings(const Player& newPlayer, vector<Player>& rankings, int maxPlayers)
{
rankings.push_back(newPlayer);
sort(rankings.begin(), rankings.end(), cmp);
if (rankings.size() > maxPlayers)
{
rankings.pop_back();
}
}
void displayRankings(const vector<Player>& rankings)
{
cout << "名次\t昵称\t积分\n";
for (int i = 0; i < rankings.size(); ++i)
{
cout << i + 1 << "\t" << rankings[i].name << "\t" << rankings[i].score << "\n";
}
}
void saveRankingsToFile(const vector<Player>& rankings, const string& filename) {
ofstream file(filename);
if (file.is_open())
{
for (int i = 0; i < rankings.size(); ++i)
{
file << rankings[i].name << " \t" << rankings[i].score << "\n";
}
file.close();
}
else
{
cout << "打开文件失败!";
}
}
void loadRankingsFromFile(vector<Player>& rankings, const string& filename)
{
ifstream file(filename);
if (file.is_open())
{
string buffer;
while (getline(file, buffer))
{
stringstream ss(buffer);
string name;
int score;
ss >> name >> score;
rankings.push_back({ name, score });
}
file.close();
}
else
{
cout << "打开文件失败!";
}
}
int main()
{
vector<Player> rankings;
int maxPlayers = 10, score;
string name;
loadRankingsFromFile(rankings, R"(C:\\文件流\\zy.txt)");
cin >> name >> score;
Player newPlayer{ name, score };
updateRankings(newPlayer, rankings, maxPlayers);
displayRankings(rankings);
saveRankingsToFile(rankings, R"(C:\\文件流\\zy.txt)");
return 0;
}