【问题标题】:How to insert numbers from a file into linked list如何将文件中的数字插入到链表中
【发布时间】:2015-05-25 06:32:20
【问题描述】:

我有这个程序,我试图在其中获取一个 txt 文件,但文件中的数字列表位于链接列表中。该文件如下所示:

test.txt

100
200
2
94 

但是当我运行程序而不是将所有数字放入链接列表时,它只插入最后一个数字94,请帮助

ma​​in.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


【解决方案1】:

您可以在readFile 函数中插入数字。

#include "list.h"
#include <fstream>
#include <iostream>
#include <cassert>
using namespace std;
bool readFile(list&li)
{
    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 (cin>>file)
    {
        li.insertElement(file);
    }
    //cout<<data<<endl;
    if (cin.bad())
        return false;
    return true;
}

int main()
{
    list mylist; 
    readFile(mylist);
}

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2017-01-03
    • 1970-01-01
    相关资源
    最近更新 更多