Because data from file look like this: line 1 is name (first last), next line is score (score1 score 2 ….score5) and so on… So I think that I need getline for name and >> for score
Example of data file
David Beckham
80 90 100 20 50
Ronaldinho Gaucho
99 80 100 20 60
....
First of all, I have structure
struct Player {
string name;
int score[5];
} player[size]
When read data from file
int i = 0;
while(!file.eof())
{
for (int j = 0; j < 2; j++) //read each 2 two lines
{
if(j==0) // name
{
getline(file, player[i].name);
}
else if(j==1) // score
{
for(int k=0; k<5; k++) file >> player[i].grade[k];
}
}
i++; //move to next player
}
Problem is after read all scores (of first player), it seems like doesn’t go to next line to continue read next name, kind of mess up there. So any suggestions to correct my code or new idea to do this?
After reading the last score, the line break is still sitting on the input buffer. You need to skip that. The
ignorefunction is useful for that.Check for errors as appropriate. The
>>operator,getline, andignoreall return the stream reference, which you can check for success or failure.There’s no need for that
jloop since each iteration does a completely different thing. Just write thej=0case immediately followed by thej=1case, and then get rid of the loop, like my code above. (And note thatjwill never equal 2 inside the loop, so your condition was wrong anyway.)