MIkey27
MIkey27

Reputation: 25

reading data from a file into an array of a class

//Student file
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;

#include "student.h"
#define cap 100
void main()
{       string s;
    class student student[cap],l;
    int i;
    fstream f;

    i=0;
    cout << "Enter the file name: ";    //Display to enter the file name
    cin >>s;


    f.open(s.data(),ios::in);
    if(!f.is_open()) 
        cout << "could not open file";
    while(i<cap && !f.eof())
    {       cout << "good";
        student[i].get(f);

//Display if okay
        if(f.good())
        {
            i++;
            student[i].put(cout);
            cout << i;
        }
    }
        f.close();

}
class student
{
    public:
        student(); //Constructor without parameters
        student(int,string,string,int,float); //Constructor with parameters
        ~student(); //Deconstructors
        bool get(istream &);    //Input
        void put(ostream &);    //Output
        int read_array(string,int);
    private:
        int id,age;
        float gpa;
        string last,first;
};

student::student()
{
    id = 0;
    first = "null";
    last = "null";
    age = 0;
    gpa = 0.0;
}
bool student::get(istream &in)
{

    in >> id >> first >> last >> age >> gpa;
    return(in.good());
}
void student::put(ostream &out)
{
    out << id << first << last << age << gpa;
}

When i run this It displays the constructor values over, and over and the data from the file that should be going into the array and displaying them. I am not sure if I am doing the right way to put the data into the class array correctly.

Upvotes: 1

Views: 1530

Answers (1)

Adam Liss
Adam Liss

Reputation: 48280

Here's one problem:

if (f.good())
{
  // student[i] has just been read from the file.
  i++;                   // Increment counter.
  student[i].put(cout);  // Print whatever was in the next element.
  cout << i;
}

The counter is incremented first, so student[i] refers to the element after the one that was just updated.

Upvotes: 1

Related Questions