I really need help with this guys. This compiles and runs but does not give me the right output.

tfile.data:

Seth 19 1.7
Austin 20 1.8
Michael 21 1.9

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
        ifstream fin;
        fin.open ("tfile.data");
        if (fin.fail())
        {
                cout <<"ERROR";
                exit(1);
        }
struct EMP
{
 string name;
 int age;
 double height;
} emp;
struct LISTNODE
        {
                EMP emp;
                LISTNODE *nxt;
                LISTNODE (EMP emp1, LISTNODE *nxt1=NULL)
                {
                        emp = emp1;
                        nxt = nxt1;
                };

        };
        LISTNODE *head = NULL;
        string number;
        while (fin >> number)
        {
                head = new LISTNODE(emp , head);
        }
        LISTNODE *ptr = head;
        while ( ptr != NULL)
        {
                cout << ptr->emp.name<<endl;
                cout << ptr->emp.age<<endl;
                cout << ptr->emp.height<<endl;
                ptr = ptr->nxt;
        }
return 0;
}

Dani AI

Generated

— the problem is exactly what pointed out: your loop never fills the EMP data before creating a node, so every node gets uninitialized fields. Also note that creating nodes at the head each time will produce a reversed list compared to the file order. Fill a temporary EMP from the file, then build the node from that temp.

EMP tmp;
while (fin >> tmp.name >> tmp.age >> tmp.height) {
    head = new LISTNODE(tmp, head);   // push-front (reverses order)
}

To preserve the file order, append to the tail instead of inserting at head:

LISTNODE *tail = NULL;
EMP tmp;
while (fin >> tmp.name >> tmp.age >> tmp.height) {
    LISTNODE *n = new LISTNODE(tmp);
    if (!head) head = tail = n;
    else { tail->nxt = n; tail = n; }
}

Extra tips: make sure you include <string> and check the read result before creating a node so you do not add a partially read record. If names can contain spaces, read whole lines and parse with istringstream. Free the list when done or use a container (std::list/std::vector) or smart pointers to avoid leaks. Finally, print the fields right after reading them (or use a debugger) to confirm the file is being parsed the way you expect.

where are you setting the emp in the node. i see this block for file input

while (fin >> number)
        {
                head = new LISTNODE(emp , head);
        }

but with this you are not doing anything. first you need pull the information into your employee struct and then add it to you list.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.