ceerie
ceerie

Reputation: 1

What could be the possible error why my code doesn't read from a file? - dynamic arraylist

So I'm creating a dynamic array list class pointer. But my constructors doesn't read anything from the file. It's not showing any error and I was able to run it. So i'm not sure if i'm missing something to link the pointer.

Implementation code

#include "S.h"

void S::setSize(int size1)
{
    size=size1;
}

S::S (ifstream& fin)
{
    int s;
    fin>>s;
    size=s;

    S *ptr = new S[s];

    string fname;
    string lname;
    string address;
    for(int i = 0; i<s; i++)
    {
        fin>>fname>>lname;
        getline(fin,address);

        ptr[i].setName(fname); //changed to i
        ptr[i].setLname(lname);
        ptr[i].setAddress(address);

        //s++;
    }
    //cout<<list[0].firstname;


list = ptr;

}
void S::print(ofstream& fout)
{
    for(int i=0; i<size; i++)
    {
        fout<<list[i].getName()<<"   "<<list[i].getLname()<<"   "<<list[i].getAddress()<<endl;
    }
}

driver code

#include "S.h"

int main()
{
    ifstream fin;
    ofstream fout;

    
}

so this is my class code. On my function implementation i have the setters implemented as well. like: void S::setName (string name1){list->firstname=name1;}

class S\
{
private:
    int size;
    string firstname;
    string lastname;
    string address;

    S* list;

public:

    S ();
    S (ifstream& fin);

void setName(string);
    void setSize(int);
    void setLname(string);
    void setAddress(string);

    string getName(){return firstname;}
    string getLname(){return lastname;}
    string getAddress(){return address;}


    int getSize(){return size;}


    void print(ofstream&);


};

Upvotes: 0

Views: 61

Answers (1)

Anton Shwarts
Anton Shwarts

Reputation: 525

You should change your for cycle. You always use 's' as index.

for(int i = 0; i<s; i++)
{
    fin>>fname>>lname;
    getline(fin,address);

    ptr[i].setName(fname);
    ptr[i].setLname(lname);
    ptr[i].setAddress(address);

    // ptr[s].setName(fname);
    // ptr[s].setLname(lname);
    // ptr[s].setAddress(address);
}

Upvotes: 3

Related Questions