20250306-Rain

1. 文件流

/*
1. 制作一个排行榜, 每次修改其数据时, 都会在文件中进行对应操作.
该排行榜可以展示名次, 昵称, 积分三个属性
每次用户可以输入昵称和积分, 来向排行榜中加入数据.
加入数据时, 如果排行榜中存储数量超过10个, 则删除最后一名的数据.
样例输入:
张三 100
样例输出:
名次| 昵称| 积分
1 测试1 1001
2 测试2 100
3 张三 100
4 测试3 10
*/
#include <iostream>
#include <string>
#include <fstream>
#include <algorithm>

using namespace std;

typedef struct Player
{
  string name;
  int score;
} Player;

bool cmp(Player x, Player y)
{
  return x.score > y.score;
}

int main(void)
{
  fstream file("data.txt");
  Player players[11] = {{"", 0}};

  string firstLine;
  getline(file, firstLine);

  int rank, i = 0;
  while (i < 10 && file >> rank >> players[i].name >> players[i].score)
  {
    i++;
  }
  cout << "please input name: ";
  cin >> players[i].name;

  cout << "please input score: ";
  cin >> players[i].score;

  i = min(++i, 10);
  sort(players, players + i, cmp);

  file.close();                                 // 关闭文件
  file.open("data.txt", ios::out | ios::trunc); // 以写入模式打开并清空文件

  file << "rank " << "name " << "score" << endl;
  for (int j = 1; j < i + 1; j++)
  {
    file << j << "    " << players[j - 1].name << "   " << players[j - 1].score << endl;
  }
  file.close(); // 关闭文件
  return 0;
}

Last updated