我正在做一个小游戏,我想制作一个排行榜。我有班级排行榜,我正在创建动态表,具体取决于排行榜中的玩家数量。所以这是EOF循环的一个。然后,我想在排行榜类中向这些动态表指向这些动态表。问题是我得到随机数而不是名称和点。对我来说,代码看起来不错。有帮助吗?
class Leaderboard
{
int max_counter;
int counter;
int *points;
string *name;
string filename;
public:
Leaderboard(string n_file)
{
counter = 0;
filename = n_file;
}
string get_file(){return filename;}
void set_counter(int n_counter)
{
max_counter = n_counter;
points = new int[n_counter];
name = new string[n_counter];
}
void add_value(string n_name, int n_points)
{
name[counter] = n_name;
points[counter] = n_points;
counter++;
}
void show()
{
for(int i=0;i<max_counter;i++)
{
cout << name[i] << " " << points[i] << endl;
}
}
};
和main:
Leaderboard *top = new Leaderboard("leaderboard.txt");
fstream file;
file.open(top->get_file(), ios::in);
if(file.good())
{
string name;
int points;
int counter = 0;
while(!(file.eof()))
{
file >> name >> points;
counter++;
}
counter--;
top->set_counter(counter);
while(!(file.eof()))
{
file >> name >> points;
top->add_value(name,points);
}
cout << "Dodano pomyslnie" << endl;
system("pause");
top->show();
file.close();
}
else cout << "Blad z plikiem!" << endl;
delete top;
break;
几个错误
while(!(file.eof()))
{
file >> name >> points;
counter++;
}
应该是
while (file >> name >> points)
{
counter++;
}
第二次错误,您不能因为您想要它而神奇地返回开始。你必须告诉它。
while (file >> name >> points)
{
...
}
file.clear(); // clear error state
file.seekg(0); // go to beginning of file
while (file >> name >> points)
{
...
}
允许我建议您在这里使用的一般方法可以进行大量改进。
现在,我们的main
知道(并且必须知道)关于Leaderboard
的内部工作的很多内容。
如果不需要的话会更好。排行榜本身应该是唯一知道其内部内容的部分。
让我走得更远:排行榜基本上只是分数的集合。它也不应该知道或关心单个分数的内部细节。
最后,让我建议您考虑使用标准库中的容器。就您而言,std::vector
似乎可以很好地工作。
#include <iostream>
#include <vector>
#include <iterator>
#include <vector>
#include <fstream>
#include <algorithm>
class score {
std::string name;
int points;
public:
friend std::istream& operator>>(std::istream& is, score& s) {
return is >> s.name >> s.points;
}
friend std::ostream& operator<<(std::ostream& os, score const& s) {
return os << s.name << ": " << s.points;
}
};
class leaderboard {
std::vector<score> scores;
public:
friend std::istream& operator>>(std::istream& is, leaderboard& l) {
std::copy(
std::istream_iterator<score>(is), std::istream_iterator<score>(),
std::back_inserter(l.scores));
return is;
}
friend std::ostream& operator<<(std::ostream& os, leaderboard const& l) {
for (auto const& s : l.scores)
os << s << "n";
return os;
}
};
int main() {
leaderboard scores;
std::ifstream in("leaderboard.txt");
in >> scores;
std::cout << "Top scoresn";
std::cout << scores;
}
当然,几乎可以肯定应该做更多的事情,例如按分数下降顺序对分数进行排序,因此首先出现了最高分数的人 - 但这是一个单独的问题。
<</p>