我正在嘗試通過鏈接列表進行歸檔。我想要做的是將每個單詞放在我的文本文件中的一個新節點上,但該程序將所有單詞放在單個節點上。對於例如,如果我的文本文件中有一行「我的名字是阿赫桑」它那麼它的輸出應該是:在鏈接列表中提交C++
我
名
是
阿赫桑
而我的程序正在打印此行。
#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();
}
而問題是什麼?順便說一句 - 也許首先使用調試器可以更快地設置以獲得任何答案 –
由於它無法將單詞複製到新節點,而是將所有單詞複製到單個節點,所以造成了什麼樣的錯誤。 –