1

I have the following class :

class Player {
string m_name;
int m_age;
string m_team;
string m_position;
double m_speed;

I'm using this function to save every one of the class members to a new line in a .txt file

void save (){
    ofstream ofS ("Players.txt", ios::app);
    ofS<<m_name<<endl;
    ofS<<m_age<<endl;
    ofS<<m_team<<endl;
    ofS<<m_position<<endl;
    ofS<<m_speed<<endl;
    }

And this function to create a vector of pointers to players from the txt file:

static /*vector<Player*>*/ void load(){
    ifstream ifS ("Players.txt");
    vector<Player*> players;
    string buffer1;
    while (ifS){
            Player* temp = new Player;
            getline (ifS, temp->m_name);
            ifS>>temp->m_age;
            getline (ifS, buffer1);
            getline (ifS, temp->m_team);
            getline (ifS, temp->m_position);
            ifS>>temp->m_speed;
            players.push_back(temp);
        }

    cout<<players.size()<<endl;
    for (int i=0; i < players.size(); i++){
        cout<<"The "<<i+1<<" player is "<<players[i]->m_name<<" "<<players[i]->m_age<<" "<<players[i]->m_team<<" "<<players[i]->m_position<<" "<<players[i]->m_speed<<endl;
    }

    }

However my program seems to only read the first player in the .txt file - the first 5 lines of the file. This makes me believe the line

while (ifS)

causes all my problems. I tried replacing it with

while (ifS.eof() != true)

or

while (getline(ifS, buffer2))

but none of them created the expected result. Any ideas on what I'm doing wrong?

Play4u
  • 87
  • 6
  • Yes, my question was answered by the proposed duplicate question. Thank you very much! Also, I'm sorry for the duplicate, but I really didn't know the same reason behind the other question's problem was responsible for mine. – Play4u Jul 01 '17 at 22:08

0 Answers0