0

I'm defining a member function for a class Queue that is essentially a linked list with nodes of class Car. I'm trying to make a class method that reads the queue from file row by row. I edited in a bunch of cout statements to track each iteration and I can see my test file is getting to the point where it's been turned into an instance of the node class. But then my output is a queue with a single node but a count attribute that reflects the nodes that disappeared. Here's my function:

void Queue::read(string filename)
{
    ifstream in;
    in.open(filename);
    Car temp;
    Car last;
    string name;
    string model;
    string plate;
    string vip;
    getline(in, name);
    while (!in.eof()) {
        last = temp;
        getline(in, name);
        getline(in, model);
        getline(in, plate);
        getline(in, vip);
        if (vip == "1") {
            temp = Car(name, model, plate, true);
        }
        else {
            temp = Car(name, model, plate, false);
        }
        count++;
        if (count == 1) {
            front = &temp;
        }
        else {
            last.next = &temp;
            back = &temp;
        }
    }
    last.next = NULL;
    in.close();
    std::cout << endl << *front;
}

I must be overlooking something here. The first getline() statement is just to get rid of a new line that gets inserted but the output function. Normally a node that's been output to file looks something like:

First Last

Model XXXX

AAA123

0

Rai
  • 13
  • 1
  • 2
    `temp` is a local variable that you reuse for all your nodes, so they all point to the same `Car`. You should use some form of dynamic memory allocation (like `std::unique_ptr`, or `std::shared_ptr`) – 1201ProgramAlarm Dec 01 '19 at 04:39
  • What are front and back? Did you mean ```last.front``` and ```last.back``` perhaps? – neutrino_logic Dec 01 '19 at 04:43
  • [Why !.eof() inside a loop condition is always wrong.](https://stackoverflow.com/q/5605125/9254539) You likely reach `EOF` on `getline(in, name);` --- then what? – David C. Rankin Dec 01 '19 at 04:50
  • Variables front and back are attributes of the Queue class showing the first and last members of the linked list. last is perhaps a poorly chosen name- I wanted to distinguish the current temp node, and the one just before it so I could link them together. – Rai Dec 01 '19 at 04:50
  • I'm unsure how to use shared or unique pointers in this situation, but I'm trying to make something work with dynamic memory. – Rai Dec 01 '19 at 05:37

0 Answers0