我有以下课程:
class Player {
string m_name;
int m_age;
string m_team;
string m_position;
double m_speed;
我正在使用此函数将每个类成员保存到.txt文件中的新行
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;
}
此函数用于从txt文件创建指向玩家的指针向量:
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;
}
}
但是我的程序似乎只读取.txt文件中的第一个播放器 - 文件的前5行。这让我相信这一行
while (ifS)
导致我所有的问题。我尝试用
替换它while (ifS.eof() != true)
或
while (getline(ifS, buffer2))
但他们都没有创造出预期的结果。关于我做错了什么想法?