描述

通过文件流实现录入用户信息和显示排行榜前十数据

练手题,写的有些乱

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

struct information
{
string name = "NULL";
int score = -1;
} info[10];

void view()
{
ifstream fin;
fin.open("./data.txt");
if (!fin.is_open())
{
cout << "读取文件失败! " << endl;
exit(1);
}
int rank;
string name;
int score;
cout << setw(20) << left << "排名" << setw(20) << left << "昵称" << setw(20) << left << "积分" << endl;
while(fin >> rank >> name >> score)
cout << setw(20) << left << rank << setw(20) << left << name << setw(20) << left << score << endl;
cout << "---------------------------------------" << endl;
fin.close();
}

void read()
{
int rank;
ifstream fin;
fin.open("./data.txt");
if (!fin.is_open())
{
cout << "读取文件失败! " << endl;
exit(1);
}
int i = 0;
while (fin >> rank >> info[i].name >> info[i].score)
++i;
fin.close();
}

void write()
{
read();
ofstream fout;
fout.open("./data.txt");
if (!fout.is_open())
{
cout << "打开文件失败! " << endl;
exit(1);
}

string name;
int score;
int rank = 1;

cout << "请输入您的昵称和积分: ";
cin >> name >> score;

if (info[0].name == "NULL")
{
fout << rank << " " << name << " " << score << endl;
}
else if (info[9].name != "NULL") // 排行榜已经有10位
{
info[9].name = name;
info[9].score = score;

// 冒泡排序
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 9 - i; ++j)
{
if (info[j].score < info[j + 1].score)
{
struct information temp;
temp = info[j];
info[j] = info[j + 1];
info[j + 1] = temp;
}
}
}

for (int i = 0; i < 10; ++i)
{
fout << i + 1 << " " << info[i].name << " " << info[i].score << endl;
}
}
else
{
int num = 0; // 统计在榜人数
for (; info[num].name != "NULL"; ++num) {}

info[num].name = name;
info[num].score = score;

// 冒泡排序
for (int i = 0; i < num; ++i)
{
for (int j = 0; j < num - i; ++j)
{
if (info[j].score < info[j + 1].score)
{
struct information temp;
temp = info[j];
info[j] = info[j + 1];
info[j + 1] = temp;
}
}
}

for (int i = 0; i < num + 1; ++i)
{
fout << i + 1 << " " << info[i].name << " " << info[i].score << endl;
}
}

cout << "---------------------------------------" << endl;
fout.close();
}

int menu()
{
int choice;
cout << "请问您需要查看还是写入文件: \n1->查看\n2->写入\n输入其他任意字符退出程序" << endl;
cin >> choice;
switch (choice)
{
case 1:
view();
return 0;
case 2:
write();
return 0;
default:
cout << "程序即将退出..." << endl;
return 1;
}
}

int main()
{
while (!menu()){}

return 0;
}