为什么我的节点临时节点不能显示正确的数据?

Why can't my Node tempNode show the right data?

本文关键字:节点 数据 不能 我的 为什么 显示      更新时间:2023-10-16

我的程序有点问题。我有一个函数void loadData()它将从文本文件加载数据customers.txt并将每一行数据存储到链表中。我关心的是,特别是I/O的工作方式。我设法将数据从文本文件获取并存储到链表数据成员变量中。当我调用该变量时,我会得到我想要打印到控制台上的答案。std::cout << "Group Name: " << tempCustomer->groupName << std::endl;

但是,我决定稍后在函数中运行控制台输出命令以测试所有变量是否都具有正确的数据,我意识到它无处不在。我不确定为什么它不起作用。

这是loadData()函数

void Groups::loadData(){
fin.open("customers.txt"); 
char holder[MAX_SIZE];
if(!fin.is_open())
std::cerr << "Could not access file" << std::endl;
else{
while(!fin.eof()){
Customers *tempCustomer = new Customers;
fin.getline(holder,MAX_SIZE,';');
tempCustomer->groupName = holder;
std::cout << "Group Name: " << tempCustomer->groupName << std::endl;
fin.getline(holder,MAX_SIZE,';');
tempCustomer->name = holder;
fin.getline(holder,MAX_SIZE,';');
tempCustomer->email = holder;

fin >> tempCustomer->choice;
fin.get(); //gets the last character, which is 'n'
fin.ignore(); //ignores the next character which is the 'n'
tempCustomer->next = NULL;
std::cout << "What does the temp Node Store?" << std::endl;
std::cout << "Group Name: " << tempCustomer->groupName << std::endl;
std::cout << "Name: " << tempCustomer->name << std::endl;
std::cout << "Email: " << tempCustomer->email << std::endl;
std::cout << "Choice: " << tempCustomer->choice << std::endl;
//addCustomerToLL(tempCustomer);
tempCustomer = NULL;
delete tempCustomer;
}    
}
fin.close();
}

这是控制台输出:

Group Name: Jonathan Group
What does the temp Node Store?
Group Name: vazquez.jonathan@pcc.edu
Name: vazquez.jonathan@pcc.edu
Email: vazquez.jonathan@pcc.edu
Choice: 2

这是文本文件customers.txt

Jonathan Group;Jonathan;vazquez.jonathan@pcc.edu;2

这是一个学校作业,我要将文本文件中的所有客户存储到链表中。我还要使用 c 字符串作为字符串,而不是字符串的 c++ 版本。让我知道其他文件是否必要,我没有包含它们,因为除了我在类中拥有的ifstream fin;私有变量和const int MAX_SIZE = 256;全局变量之外,此函数中没有任何内容利用func之外的任何其他内容。

假设不允许使用std::string,您需要为每个字符串分配内存。

所以替换这个:

fin.getline(holder,MAX_SIZE,';');
tempCustomer->groupName = holder;

跟:

fin.getline(holder, MAX_SIZE, ';');
char *s = new char[strlen(holder) + 1];
strcpy(s, holder);
tempCustomer->groupName = s;

当您不再需要分配的内存时,您应该释放它,因此请为Customers类创建一个析构函数:

Customers::~Customers()
{
delete[] groupName;
}

这是因为当您读取新行时holder会发生变化,但Customer中的所有字符串都指向存储您读取的最后一行的同一holder。 将nameemail等的类型更改为char[MAX_SIZE]可能会有所帮助。