我正在做一个小游戏,我想做一个排行榜。我有班级排行榜,我正在创建动态表,这取决于leaderboard.txt中有多少玩家。这是一个while 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;发布于 2019-03-16 04:55:24
几个错误
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)
{
...
}发布于 2019-03-16 05:25:50
请允许我建议,您在这里使用的一般方法可以进行相当大的改进。
现在,我们的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 scores\n";
std::cout << scores;
}当然,还有更多几乎肯定应该做的事情,比如按分数降序排列分数,这样得分最高的人就会首先出现--但这是一个单独的问题。
https://stackoverflow.com/questions/55190446
复制相似问题