我的程序有点问题。我有一个函数 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;
之外,此函数中没有任何东西使用 func 之外的任何其他文件。我在类里面的私有(private)变量和const int MAX_SIZE = 256;
全局变量。
最佳答案
假设您不允许使用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;
}
关于c++ - 为什么我的节点 tempNode 不能显示正确的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50205664/