c++ - C++ OOP, problem with reading file, EOF used two times, leaderboard
问题描述
I am working on a little game and I want to make a leaderboard. I have class leaderboard and I am creating dynamic table, depending on how many players in the leaderboard.txt are. So that's one while eof loop. Then i want to asign names and points to these dynamic tables in leaderboard class. Problem is that i get random numbers instead of names and points. For me the code looks good. Any help?
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)
{
...
}
推荐阅读
- json - 尝试从 CRA 应用程序中的 json 路径加载图像时出现问题
- python - Webscrape 像thingiverse这样的产品网站
- javascript - 如何在滚动时更改垂直菜单的大小
- flutter - 颤动的未来
' 不是 'Widget' 类型的子类型 - c++ - 矩阵条件不输出结果 C++
- javascript - 如何从 axios 中检索数据并将其填充到 Vue.js 中的编辑表单(选择选项)中?
- r - 将gglot导出到多个excel工作簿
- javascript - html表对调整大小的反应
- java - 如何使用 logback 以文本和 json 格式打印 Spring Boot 日志?
- python - 如何将两个单独的 python proram 加入一个文件?