Problem with reading file (ifstream)

greatUnited

Name (space) Goals Scored

Josh (space) 1,0,1,-,0,1
George (space) 0,1,0,0,2,0
Nathan (space) 0,0,-,-,1,0
Andy (space) 0,0,1,0,-,-
Eric (space) 1,0,0,-,-,2



Let's think above one is text file. The file name is goalScorers.txt
(space)<< space is not included in the actual text file.I was trying to explain that there is a space between letters in the actual text.

I would like to read that above file. Here is my incomplete following code.

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

struct Player
{
string name;
int goals;
int totalGoals ;
};

const int MAX_PLAYERS = 25;

int main(int argc, char *argv[])
{

ifstream scorerFile

char scorerFileName[20] ;
do
{
cout << "Enter file containing data about goal scorers: " ;
cin >> scorerFileName ;
scorerFile.clear() ;
scorerFile.open(scorerFileName) ;
}
while(!scorerFile.good()) ;
That was my half of my code.What i want to read is that i want count the goal score of each player. Can some1 show me the way how to continue with my code? Help need pls....

Regard,
Nay
Last edited on
1
2
3
4
5
6
struct Player
{
string name;
int goals;
int totalGoals ;
};

Shouldn't goals be an array of 5 ints?

Make an array of players like this: Player players[MAX_PLAYERS];

Then use a for loop with the loop variable iterating from 0 to MAX_PLAYERS-1 and read the data of each element of your players array. If scorerFile.good()==false break the loop. It would also be useful to have a variable to hold the actual number of players inputted.

Use the >> operator to get the string, then ignore the space with get(), and then get the rest of the data. I would use peek() to check the next char. If it was an digit I'd use operator >> to get the whole number. If it's not a digit (i.e. it is a '-') get it with get(). Also use get() to read the commas and the newline character.

Try to solve it and tell me if you have a problem somewhere.
Topic archived. No new replies allowed.