【发布时间】:2015-05-25 06:32:20
【问题描述】:
我有这个程序,我试图在其中获取一个 txt 文件,但文件中的数字列表位于链接列表中。该文件如下所示:
test.txt
100
200
2
94
但是当我运行程序而不是将所有数字放入链接列表时,它只插入最后一个数字94,请帮助
main.cpp
#include "list.h"
#include <fstream>
#include <iostream>
#include <cassert>
using namespace std;
int readFile()
{
int file;
ifstream fin;
string fn;
cout<<"enter the name of a file "<<endl;
cin>>fn;
fin.open(fn.c_str());
assert (fin.is_open());
//reads integer data from a file and prints the data
while (true)
{
fin>>file;
if (fin.eof())
{
break;
}
}
//cout<<data<<endl;
return file;
}
int main()
{
list mylist;
mylist.insertElement(readFile());
}
list.cpp
#include "list.h"
list::list()
{
head=NULL;
}
void list::insertElement(int element)
{
node *temp, *curr, *prev;
temp = new node;
temp->item = element;
numberofelements++;
for(prev = NULL, curr = head/*value set*/; (curr !=NULL)&&
(temp->item>curr ->item)/*condition*/;
prev = curr, curr = curr->next/*loop expression*/);
if (prev == NULL)
{
temp-> next = head;
head = temp;
}
else
{
temp -> next = curr;
prev -> next = temp;
}
}//end of function
list.h
#include<cassert>
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
struct node
{
int item;
node *next;
};
class list
{
public:
list();
void insertElement(int element);
private:
node *head;
};
【问题讨论】:
-
你将每一行读入同一个int,覆盖最后一个值,然后返回。所以你只得到最后一个数字。您可能想使用
std::vector,或者从读取数字的循环中调用 insert。 -
assert仅在调试模式下编译,不应用于检查文件,这可能在发布模式下失败。问题是您一次从文件中读取一个整数并将它们存储在file中,但您不会将它们存储在任何地方。下次执行 while 循环时,将丢弃过去的数字。
标签: c++ file linked-list