为什么我的节点临时节点不能显示正确的数据?
Why can't my Node tempNode show the right data?
我的程序有点问题。我有一个函数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
。 将name
、email
等的类型更改为char[MAX_SIZE]
可能会有所帮助。
相关文章:
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 如何在Visual C+++中从JSON文件中读取节点数据
- 修改链表主函数代码,用户将在其中输入节点的索引和数据以及正确的消息
- 如何在C++中实现节点数任意的通用树数据结构?
- 如何在C++中使用带有SFML的http reqest从节点.js服务器获取数据?
- 如果我们不创建一个新节点并使用指针插入数据并建立链接(在链表中)怎么办?
- 使用 Broadcast 发出的从节点服务器发送的数据不能被 C++ 套接字 IO 客户端读取
- C++ Eclipse:二叉搜索树节点>数据=变量似乎不起作用
- C++ 在节点内存储对数据对象的引用,而不复制数据
- 如何通过其持有的数据从链表中删除某个节点?
- 基于给定字符串数据类型的链表删除节点
- 为什么我的节点临时节点不能显示正确的数据?
- C++中的数据结构,插入链表中节点的开头
- 从链表数组访问节点数据
- 如何取消引用作为指针的链表节点数据
- 如何将XML节点数据转换为QT中的字符串
- 无法访问类中的节点数据
- C++ 使用 std::p air 模板专用化定义树节点数据结构
- 如何使用pugixml解析获得具有相同节点名称的节点的节点数据
- 如何添加备用节点数据