c++ - 为什么我的 Node tempNode 不能显示正确的数据?
问题描述
我的程序有点问题。我有一个函数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;
}
推荐阅读
- azure-active-directory - 应用程序图标未显示在 https://portal.office.com/account/#apps
- apache-spark - 在 Spark-Streaming 中,执行器上的活动任务是否可能比内核数更多?
- android - Android系统导航栏背景颜色
- android - Android没有显示所有通知
- arrays - 对对象数组中的多个属性求和
- python - 重命名在 Django admin 中上传的文件并省略表单中的字段
- mysql - 如何在 Ansible 中运行 MySQL 查询
- android - 在 RecyclerView 适配器的 onBindViewHolder 中获取上下文
- ruby-on-rails - Rails 在不同模型上的自定义验证
- java - 发送 html 电子邮件