Reading from txt file into a linked list

I am attempting to read data from a *.txt file into a linked list. The file is set up with 16 different types of data arranged into rows, with tabs between each data type. I am having several problems with this. The compiler gives no errors, but when I run the program and enter the file name to be read from, nothing happens. I tried replacing the while(!din.eof()) line (line 27 below) with a for loop for(int i=0; i<NUM_LINES; i++), and this seemed to help, but I was given the first three elements (all string types) followed by a row of zeroes, with this line repeating until the end of the loop. I've included the method in which I believe the problem is located below. I was wondering if someone could take a look at my code and let me know where the problem is. Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
bool readData()
{
   // Declare local variables
   string name, position, team;
      name = position = team = "";
   int g, att, cmp, yds, lng, td, inte, sck, sckyl;
      g = att = cmp = yds = lng = td = inte = sck = sckyl = 0;
   float attg, pct, ydsg, rating;
      attg = pct = ydsg = rating = 0.0;

   // Get file name
   string filename = "";
   cout << "Enter file name: ";
   cin >> filename;

   // Open input file
   ifstream din;
   din.open(filename.c_str());
   if (din.fail())
   {
      cerr << "Could not open file: " << filename << endl;
      return false;
   }

   // Read data
   Node *head = NULL;
   while (!din.eof())
   {
      din >> name >> position >> team >> g >> att >> attg >> cmp >> pct >> yds >> ydsg >> lng >> td >> inte >> sck >> sckyl >> rating;

      Node *temp = new Node(name, position, team, g, att, attg, cmp, pct, yds, ydsg, lng, td, inte, sck, sckyl, rating);
      temp->setNext(head);
      head = temp;
   }

   din.close();
   head->print();
   return true;
}
I'm also new to linked list. Here's what I think.

Line 33. head should only be updated if it is NULL. If you intend to read the list again from the beginning.

You might also need another Node pointer, which is the current node pointer (e.g., CurNode) so that you don't have to keep starting from the head looking for the end of the list.

Line 32: Might need to set the Node pointer of temp to point to NULL to mark the end of the list. Then, point the Node pointer of the current node (CurNode) to the newly allocated node, which is temp.

inside the print function traverse the list starting from head until you reach the end marker, which is NULL.
Topic archived. No new replies allowed.