2013-04-16 107 views
0

我试图从文件读取链接列表。但由于某种原因,它甚至没有阅读文件的内容。从文件读取链接列表C++

这是文件的结构:

Product 1 
Category 
22.33 
Product 2 
Category 
44.23 
Product 3 
Category 
66.55 

,这是读取该文件的内容的功能。它会调用addproduct函数以按排序顺序添加它所读取的项目。

void load (NodePtr head) 
     { 
      // create a variable to attach to the file 
      ifstream input; 
      input.open("data.txt"); 

      // check to see if the file opened correctly, and if not, exit program 
      if (input.fail()) 
      { 
       cout << "\n Data file not found \n"; 
       return; 
      } 
      ListItemType data; 


      while((! input.eof()) && (head != NULL)) 
      { 
       input >> data.productname; 
       input >> data.category; 
        input >> data.productprice; 

       addproduct(head, data); 
      } 
+0

为什么是head!= NULL呢?每次调用函数时,头部可能都是空的,因为在调用函数之前头部没有数据。 – tay10r

+0

你是否期望任何错误,如果请释放错误信息,我认为你的代码是好的,而条件你可以使用input.good() – saeed

+0

也,如果head!= NULL不是问题,它看起来不像你的当函数返回时接收头的新指针。这可能会也可能不会成为问题,具体取决于它是否为fifo列表 – tay10r

回答

0

您需要接收head的新指针。而不是返回void,返回NodePtr。

NodePtr load(NodePtr head){ 

    ... 
    return head; 
} 
+0

OP在做什么是可以接受的。他正在检查'head'是否为'NULL'(它可能是),在调用'addproduct()'之前不检查他是否可能发送可能导致段错误的NULLed指针。 –

+0

好吧,我是在addproduct分配内存的列表下的假设。 – tay10r

+0

摆脱(head!= NULL)导致错误并返回nodeptr仍然不起作用 – user1896464