Read From File & Insert into Linked List

Hey everyone, so I have a program and function i'm having an issue understanding. Here is what it's doing in the main.

1
2
3
4
5
6
7
int main()
{
    orderedLinkedList<MemberDO> memberList;
    MemberDO::readFromFile("Member.dat", memberList);

    return 0;
}


So it is creating a linked list object using the MemberDO class type which has a int, string, char and double. Then it will call the readFromFile static function in the MemberDO. So this is where my problem is I have this function

1
2
3
4
void MemberDO::readFromFile(char *fname, orderedLinkedList<MemberDO>& list)
{

}


How do I read in each individual data member from the input then create a new MemberDO object and insert the objects into the linked list specified in the second argument list?

Here is the MemberDO class declarations

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class MemberDO
{
private:
    int key;
    string lastName;
    char firstInitial;
    double dues;
    
public:
    MemberDO(){};
    MemberDO(int k, string l, char i, double d) : key(k), lastName(l), firstInitial(i), dues(d){};
    void setKey(int);
    void setLastName(string);
    void setFirstInitial(char);
    void setDues(double);
    int getKey();
    string getLastName();
    char getFirstInitial();
    double getDues();
    static void readFromFile(char*, orderedLinkedList<MemberDO>&);
};

If you need any other code let me know wanted to make this short and to the point. Any help would be great.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void MemberDO::readFromFile(const char *fname, orderedLinkedList<MemberDO>& list)
{
    std::ifstream ifs(fname);
    if (!ifs)
    {
        std::cerr << "File read error!\n";
        return;
    }

    std::string lname;
    int key;
    char fi;
    double dues;

    while (ifs >> lname >>  key >> fi >> dues)
    {
        list.insert(MemberDO(key, lname, fi, dues));
    }
    
    std::cout << "Finished!\n";
}
Last edited on
Awesome, thanks! I was actually doing my while loop like that but I guess I didn't think I had to define those types again so when I was putting the actual variable names from MemberDO it was giving me an error. If you can clarify for me why do I need to make the int, string, char, double over again? I know they are private but isn't it technically still part of the class, can't it use those private vars?

Edit: is it because the function is static that it can't use those vars in the private memberDO?
Last edited on
Static methods do not bind to an instance of a class. So since they are not called as a result of an actual object invoking them, they cannot have access to private members of a non-existent object
Great thank you very much! Appreciate the help.
Topic archived. No new replies allowed.