在链表c++中归档

Filing in linked list c++

本文关键字:c++ 链表      更新时间:2023-10-16

我正在尝试通过链表进行归档。我想做的是将文本文件中的每个单词放在一个新节点上,但这个程序将所有单词放在单个节点上。例如,如果我的文本文件中有一行"我的名字是ahsan",那么它的输出应该是:

我的

名称

ahsan

而我的程序正在按原样打印这行。

#include <iostream>
#include<fstream>
using namespace std;
class node
{
public:
string data;
node*next;
};
class mylist
{ 
public:
node*head;
mylist()
{
    head=NULL;
}
void insertion(string item)
{
    node* temp= new node;
    temp->data=item;
    temp->next=NULL;
    temp->next=head;
    head=temp;
}
void print()
{
    node*ptr;
    if(head==NULL)
    {
        cout<<"List empty :"<<endl;
        return;
    }
    else
    {
        ptr=head;
        while(ptr!=NULL)
        {
            cout<<ptr->data<<endl<<endl;
            ptr=ptr->next;
        }
    }
 }
 };
int main()
{
ofstream myfile;
ifstream infile;
string mystring;
mylist l;
//  myfile.open ("ahsan.txt");
//  myfile << "Ahsan's first file.n";
//  myfile.close();
string lol;
infile.open("ahsan.txt");
while(!infile.eof())
{
    getline(infile,lol);
    l.insertion(lol);
}
l.print();
infile.close();
}

这是因为您使用了getline。getline按行阅读文本,而不是按单词阅读。相反,您可以使用输入流来完成此操作。

infile >> myString;

它将读取每个单词,假设你想按空格分割。。。