saving file to memory

I need to add a statement to the body of the
while loop so that the score will be saved in the array GPA. I've tried finding a forum already because this seems like it should be incredibly easy but I haven't figured out how yet. Here is my code:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream infile;
string name;
double score;
int size = 0; // size of data file (keeps track of the num of
records)

infile.open("datafile"); // open the file 'datafile'
if (infile.fail()) // if unable to open, show an error msg
{
cout << "ERROR: can't open file!" << endl;
exit(1);
}

infile >> name >> score; // read the first student's data
while(! infile.eof()) // as long as we have not reached the
end of file
{
size++; // update the num of records
cout << name << score; // output student record
infile >> name >> score; // get another student's data

}

cout << "Number of students = " << size;
infile.close();
}
Last edited on
To help you out, I need a little more information:

1. Are there more than one record per student?
2. Is the file sorted?

Also, I find it easer for totals to do all of your reads within the while-loop. In your code, you will have to store the first student's name and score outside of the loop, and you have to add extra code to calculate your GPA. I suggest the following change:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

...

    while( 1 )
        {
        infile >> name >> score;

       if( infile.eof() )
           break;

       /*    Other processing here    */

       }    /*    while( 1 )    */
I'm sorry, this programs purpose is to call the file "datafile" and display its contents. The datafile that is displayed looks like this

Anderson 3.4
Beckman 2.7
Bishop 1.6
Chapman 3.7
Ellis 1.0
Ford 2.5
Gilmore 3.0

Number of students = 7

So there's no calculations the program needs to perform, just display and save its contents to GPA array
Even easier. Just assign each name and score to the GPA array.
@kooth: that can be simplified (and improved) to:

1
2
3
4
while(infile >> name >> score)
{
    vec.push_back(GPA(name, score));
}

Assuming we have a GPA struct:

1
2
3
4
5
6
7
struct GPA {
    std::string name;
    double score;

    GPA(const std::string& s, double n)
    :name(s), score(n) { }
};

and vec is a std::vector<GPA>.
It certainly can filipe; however, Sariss1990 is talking about an array, and I'm guessing that Sariss1990 hasn't gotten to the STL yet.
The vector was more of a filler. I meant improved and simplified by this:

while(infile >> name >> score)

This way, we break out of the loop if the stream goes into a eof(), fail() or bad() state. You weren't checking for fail() or bad().
Correction filipe, it is Sariss1990 who was not checking for fail() or bad(). :)
Topic archived. No new replies allowed.