[英]C++ OOP, problem with reading file, EOF used two times, leaderboard
我正在做一個小游戲,我想做一個排行榜。 我有排行榜類,並且正在根據leaderboard.txt中有多少名玩家創建動態表。 因此,這是一個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;
}
}
};
AND 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 scores\n";
std::cout << scores;
}
當然,還有更多幾乎可以肯定的事情要做,例如按照分數降序對分數進行排序,因此得分最高的人首先出現-但這是一個單獨的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.