通过从几乎工作的文本文件中读取来将节点附加到链表

Appending nodes to linked list by reading from text file almost working

大家好!我有一个程序,它有一个链表,其中每个节点都有一个字符串名称和一个用于各自名称的 ID 的 int,追加、前置、插入后、删除等函数工作正常,但我需要实现以便它从一个文本文件中读取,示例:

使用此代码

case 9:
        {
            file.open("Attendance.txt");
            while (!file.eof())
            {
                file>>node->attendeename>>node->key;
                attendance.appendAttendee(node);
            }
        cout << "imported\n";
        }
        break;

当我尝试 运行 该选项时,它仅将文本文件的最后一行附加为节点,console:

这是完整的程序代码,程序的其余部分是与朋友和网络资源合作完成的,我不声称这是我自己的

#include <iostream>
#include <iomanip>
#include <bits/stdc++.h> 
#include <sstream>
#include <fstream>
using namespace std;

//linked list node
class Node {
  public:
  int key;
  string attendeename;
  Node* next;
};


class LinkedList {
  public:
    Node * head;
    //default constructor
  LinkedList() {
    head = NULL;
  }
  //Have head point to the node
  LinkedList(Node * n) {
    head = n;
  }

  // Checks if node exists using key value 
  Node * keyAlreadyExists(int k) {
    Node * check = NULL;      
    Node * ptr = head;
    while (ptr != NULL) {
      if (ptr -> key == k) //checks if k already exists as a key
       {
        check = ptr;
      }
      ptr = ptr -> next;
    }
    return check;
  }

  //Append a node to the end of the list
  void appendAttendee(Node * n) {
    if (keyAlreadyExists(n -> key) != NULL) //first checks if a node already exists with n -> key 
    {
      cout << "----- Node Already exists with key value : " << n -> key << ". Append another node with different Key value -----" << endl << endl;
    }
    else
    {
      if (head == NULL) //checks if list is empty
      {
        head = n;  //the node becomes the head of the list
        cout << "----- Node Has Been Appended -----" << endl << endl;
      }
      else
      {
        Node * ptr = head;
        while (ptr -> next != NULL) //traverses to the end of the list
        {
          ptr = ptr -> next;
        }
        ptr -> next = n;  // the current last node will now point to the passed node    
        cout << "----- Node Has Been Appended -----" << endl << endl;
      }
    }

  }
  // add node to the start of the list
  void prependAttendee(Node * n) {
    if (keyAlreadyExists(n -> key) != NULL) //first checks if a node already exists with n -> key 
    {
      cout << "----- A Node Already exists with key value : " << n -> key << ". Append another node with different Key value -----" << endl;
    }
    else  
    {
      n -> next = head; //makes node n point to the address of head
      head = n;
      cout << "----- Node Has Been Prepended -----" << endl << endl;
    }
  }

  // insert a node after a specific node in the list
  void insertAttendee(int k, Node * n) {
     if (head == NULL) //checks if their is already a node in the list
    {
      cout << "----- Attendance list is still empty, can't add after key-----" << endl << endl;
    } else {
    Node * ptr = keyAlreadyExists(k); //checks if the int k that is passed does exist inside the list
    if (ptr == NULL)
    {
      cout << "----- No node exists with key value: " << k << " -----" << endl << endl;
    }
    else
    {
      if (keyAlreadyExists(n -> key) != NULL) //checks if the key in the new node to be added, already exists in the list
      {
        cout << "-----A Node Already exists with key value : " << n -> key << ". Append another node with different Key value -----" << endl << endl;
      }
      else
      {
        n -> next = ptr -> next; //makes the newly added node point to the node that the previous node was pointing to
        ptr -> next = n;  //links the node that has the chosen key point to the new node
        cout << "----- Node Has Been Inserted -----" << endl << endl;
      }
    }
  }
}

  // Delete a node that has the key int k
  void deleteAttendee(int k) {
    if (head == NULL) //checks if their is already a node in the list
    {
      cout << "----- Attendance list already empty. Cannot delete anymore -----" << endl << endl;
    } else if (head != NULL) {
        //checks if int k belongs to the key of head node
      if (head -> key == k) {
        head = head -> next; //makes head pointer point to the node after the head node 
        cout << "----- Attendee with key ID " << k << " deleted -----" << endl << endl;
      } else {
        Node * temp = NULL;
        Node * prevptr = head;
        Node * currentptr = head -> next;
        while (currentptr != NULL) {
            //checks if the key of currenptr is int k
          if (currentptr -> key == k) {
            temp = currentptr;
            //gets rid of the node of currentpr
            currentptr = NULL;
          } else {
            //moves on to the next node
            prevptr = prevptr -> next;
            currentptr = currentptr -> next;
          }
        }
        //checks if a node has been deleted
        if (temp != NULL) {
            //makes the previous pointer point to the node after the deleted node
          prevptr -> next = temp -> next;
          cout << "----- Attendee with key ID " << k << " deleted -----" << endl << endl;
        } else {
          cout << "----- Attendee doesn't exist with key ID " << k << " -----" << endl << endl;
        }
      }
    }

  }
  // update the info of a node with a specific key
  void updateAttendeeInfo(int k, string name) {
    //checks if a node with key int k exists
    Node * ptr = keyAlreadyExists(k);
    if (ptr != NULL) {
     //updates the data of the node
      ptr -> attendeename = name;
      cout << "----- Information Updated Successfully -----" << endl << endl;
    } 
      //output if no node contains the key int k    
      else {
      cout << "----- No Attendee has this key ID " << k << " -----" << endl << endl;
    }

  }

  // function to print the entire linked list
  void printAttendanceList() {
    //checks if the linked list contains any nodes
    if (head == NULL)
    {
      cout << "----- No attendees recorded in list -----";
    }
    else
    {
      cout << endl << "----- List of Attendees -----" << endl;
      Node * temp = head;
      //to print the key and data of every node in the list
      while (temp != NULL)
      {
        cout << "Name: " << temp -> attendeename << setw(7) << "ID: " << temp -> key;
        temp = temp -> next;
        cout << endl;
      }
    }
    cout << endl << endl;

  }
  
  
  //function to output the entire linked list to text file
  void backupAttendanceList()
  {
    ofstream file("Attendance.txt");
    Node * temp = head;
      //to print the key and data of every node in the list
      while (temp != NULL)
      {
        file << temp -> attendeename << setw(7) <<  temp -> key;
        temp = temp -> next;
        file << endl;
      }
      cout << "----- Attendance list backed up successfully -----" << endl << endl;
  }
  


}   ;

int main() {

  LinkedList attendance;
  int choice, id, nodekey;
  fstream file;
  string name;
  
  //menu screen
  do {
    //new node;
    Node * node = new Node();
    cout << "Welcome to the event! Please select option to do from the registration menu:" << endl << endl;
    cout << "1 - Add attendance" << endl;
    cout << "2 - Insert attendance on front of list" << endl;
    cout << "3 - Insert attendance after certain key ID" << endl;
    cout << "4 - Delete attendance by key ID" << endl;
    cout << "5 - Update attendance details by key ID" << endl;
    cout << "6 - Print list of attendees" << endl;
    cout << "7 - Clear screen" << endl;
    cout << "8 - Backup to text file" << endl;
    cout << "9 - Import from text file" << endl;
    cout << "10 - Exit Program" << endl << endl;

    cout << "Your Choice: "; cin >> choice;
    cout << endl;
    

    switch (choice) {
    
    //add attendance
    case 1:
      cout << "Add your attendance details. Please enter the following:" << endl 
      << "Key Data: "; 
      cin >> id;
      cin.ignore();
      cout << "Name: ";
      getline (cin,name);
      cout << endl;
      node -> key = id;
      node -> attendeename = name;
      
      attendance.appendAttendee(node);

      break;

    //insert attendance to top
    case 2:
      cout << "Insert attendance from top of list. Please enter the following:" << endl 
      << "Key Data: "; 
      cin >> id;
      cin.ignore();
      cout << "Name: ";
      getline (cin,name);
      cout << endl;
      node -> key = id;
      node -> attendeename = name;
      
      attendance.prependAttendee(node);
      break;

    //insert attendance after a certain node
    case 3:
      cout << "Insert attendance. After which key ID you want to be inserted? " << endl
      << "Key ID of attendee you want to insert after: ";
      cin >> nodekey;
      cout << "Add your attendance details. Please enter the following:" << endl 
      << "Key Data: "; 
      cin >> id;
      cin.ignore();
      cout << "Name: ";
      getline (cin,name);
      cout << endl;
      node -> key = id;
      node-> attendeename = name;

      attendance.insertAttendee(nodekey, node);
      break;

    //deletion of attendance
    case 4:

      cout << "Delete attendance. Please enter key ID to be deleted: ";
      cin >> nodekey;
      cout << endl;
      
      attendance.deleteAttendee(nodekey);
      break;
      
    //update attendance
    case 5:
      cout << "Update existing attendance. Please enter the following:" << endl
      << "Key Data: ";
      cin >> id;
      cin.ignore();
      cout << "Updated Name: ";
      getline (cin,name);
      cout << endl;
      
      attendance.updateAttendeeInfo(id, name);
      break;
    
    //print recorded list
    case 6:
      attendance.printAttendanceList();
      break;
    
    //clears console screen
    case 7:
      system("cls");
      break;
    
    //creates txt file  
    case 8:
        attendance.backupAttendanceList();
        break;
    
    case 9:
        {
            file.open("Attendance.txt");
            while (!file.eof())
            {
                file>>node->attendeename>>node->key;
                attendance.appendAttendee(node);
            }
        cout << "imported\n";
        }
        break;
    //exits the program
    case 10:
        cout<< "Now closing program" <<endl;
        exit(1);
        
    default:
      cout << "Invalid Option Number Entered, Enter Again:" << endl;
    }

  } while (choice != 10);

  return 0;
}

主要问题是您重复追加同一个节点。

Node* node = new Node();
...
while (!file.eof())
{
    file>>node->attendeename>>node->key;
    attendance.appendAttendee(node);
}

您的代码应该为文件中的每个项目创建一个新节点,如下所示

while (!file.eof())
{
    Node* node = new Node();
    file>>node->attendeename>>node->key;
    attendance.appendAttendee(node);
}

我不认为我说这段代码中可能有多个问题(我可以立即看到另一个)是不合时宜的。但我会留给你去找出那些。