Search code examples
c++ifstream

C++ loading Data from a dat file using ifstream


I'm working on a project for school where a part of what we have to do is to save data, in the form of team name followed by several integers into a .dat file and retrieve that data when the program is next run.

Note: counter is a variable that keeps count of the amount of teams that are present in the file, in this instance set to 3

    void load(int counter)
    {
        ifstream infile("saveFile.dat");
        string temp[25];
        int temp2[25][8];

        for (int i = 0; i < counter; i ++)
        {

            getline(infile, temp[i]);

            for (int j = 0; j < 7; j++)
            {
                infile >> temp2[i][j];
            }

        }

        cout << counter;

        for (int i = 0; i < counter; i++)
        {
            string name = temp[i];
            int gamesPlayed = temp2[i][0], wins = temp2[i][1], draws = temp2[i] 
   [2], losses = temp2[i][3],
                goalsFor = temp2[i][4], goalsAgainst = temp2[i][5], points = 
    temp2[i][6];
            CFootballTeam t(name, gamesPlayed, wins, draws, losses, goalsFor, 
    goalsAgainst, points);
            table[i] = t;
        }
    }

This is what my load function looks like but it appears to get stuck on the second line in the file and returns a white space followed by -858993460 for every team after the first suggesting that it's not reading any data even though data is present, here are the contents of my saveFile.dat file:

Manchester United
3 4 4 4 5 4 5
Manchester City
3 4 4 4 4 4 5
Chelsea
4 4 4 4 4 4 5

Can anyone tell me how to get the program to continue reading the rest of the lines, not just line 1 and 2?

Thanks


Solution

  • The problem is that you are not reading what you are expecting to. When you do getline(), the program reads in everything in the stream, until it hits a \n, then discards it. When you do >>, it reads until it hits white-space, but leaves that white-space in the stream. What this means is that when you go through the first iteration, you have everything good, but on the last >>, you are leaving the \n character. Then when you do the next getline(), it reads in the \n, giving an empty string and then you do >> on the text, and you are no longer putting everything in the right variables. Your input would look something like this:

    Original Data
    Manchester United\n
    3 4 4 4 5 4 5\n
    Manchester City\n
    3 4 4 4 4 4 5\n
    Chelsea\n
    4 4 4 4 4 4 5\n
    
    After getline()
    3 4 4 4 5 4 5\n
    Manchester City\n
    3 4 4 4 4 4 5\n
    Chelsea\n
    4 4 4 4 4 4 5\n
    
    After >>
    \n
    Manchester City\n
    3 4 4 4 4 4 5\n
    Chelsea\n
    4 4 4 4 4 4 5\n
    

    This means the compiler will likely set the values to some default, in your case, it looks like it is the minimum value. Ally you need to do is add inFile.ignore() at the end of each iteration to clear the \n from the end of the integers line.