首页 > 解决方案 > 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;

标签: c++

解决方案


几个错误

            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)
            {
                ...
            }

推荐阅读