为什么我的Node tempNode无法显示正确的数据?

时间:2018-05-07 00:19:39

标签: c++ file-io linked-list

我的程序有点问题。我有一个函数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之外的任何其他内容。

2 个答案:

答案 0 :(得分:2)

假设您不允许使用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;
}

答案 1 :(得分:1)

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