外部ファイルを読み取り、それぞれの名前を新しいノードにする読み取り機能があり、作成したリストに基づいて構築したいのですが、どういうわけかリストにギャップがあります
example:
I enter in dave, jack, dog, cat.
result:
name: dave
name: jack
name: dog
name: cat
それはそれを印刷します、そしてそれは今のリストです。しかし、プログラムを閉じて再度実行すると、読み取り関数がそれらの名前を読み戻し、リンクリストを再度作成します。しかし、別の名前「bob」を追加することを選択した場合。次のノードに配置します
example:
I enter in bob
result:
name: dave
name: jack
name: dog
name: cat
name: [BLANK LINE]
name: bob
6.cpp
#include "6.h"
int main()
{
petAdoption adopt;
char response;
adopt.read();
do {
adopt.enroll();
adopt.display();
cout << "Another? (y/n): ";
cin >> response;
cin.ignore(100,'\n');
} while (toupper(response) == 'Y');
}
petAdoption::petAdoption()
{
head = NULL;
}
void petAdoption::enroll()
{
char temp[TEMP_SIZE];
cout << "Name: ";
cin.getline(temp, TEMP_SIZE);
pet.name = new char[strlen(temp)+1];
strcpy(pet.name, temp);
newNode = new animal;
newNode->name = pet.name;
newNode->next = NULL;
if (NULL == head)
{
head = newNode;
current = newNode;
}
else
{
current = head;
while (current->next != NULL){
current = current->next;
}
cout << "adding node to the end of the list" << endl;
current->next = newNode;
current = current->next;
}
ofstream write;
write.open("pets.txt", ios::app);
write << current->name << '\n';
write.close();
}
void petAdoption::display()
{
current = head;
while (NULL != current)
{
cout << "Pet's name: " << current->name << endl;
current = current->next;
}
}
void petAdoption::read()
{
ifstream read;
char temp[TEMP_SIZE];
read.open("pets.txt");
if(!read)
{
cout << "/#S/ There are no pets" << endl;
}
else{
while(!read.eof())
{
read.getline(temp, TEMP_SIZE);
pet.name = new char[strlen(temp)+1];
strcpy(pet.name, temp);
newNode = new animal;
newNode->name = pet.name;
newNode->next = NULL;
if (NULL == head)
{
head = newNode;
current = newNode;
}
else
{
current = head;
while (current->next != NULL){
current = current->next;
}
current->next = newNode;
current = current->next;
}
}
}
read.close();
}
6.h
#include <iostream>
#include <cctype>
#include <cstring>
#include <fstream>
using namespace std;
const int TEMP_SIZE = 250;
struct animal
{
char *name;
animal *next;
};
class petAdoption
{
public:
petAdoption();
//~petAdoption();
void enroll();
void read();
void display();
private:
animal *head, *current, *newNode;
animal pet;
};