2015-11-22 37 views
-1

我正在嘗試通過鏈接列表進行歸檔。我想要做的是將每個單詞放在我的文本文件中的一個新節點上,但該程序將所有單詞放在單個節點上。對於例如,如果我的文本文件中有一行「我的名字是阿赫桑」它那麼它的輸出應該是:在鏈接列表中提交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(); 

} 
+0

而問題是什麼?順便說一句 - 也許首先使用調試器可以更快地設置以獲得任何答案 –

+0

由於它無法將單詞複製到新節點,而是將所有單詞複製到單個節點,所以造成了什麼樣的錯誤。 –

回答

2

那是因爲你使用getline。 getline每行讀取文本,而不是每個單詞。相反,你可以使用你的輸入流來做到這一點。

infile >> myString; 

將每個字的讀,假設你想空間分割它...

+0

謝謝你的答案,它解決了我的問題,但鏈接列表正在以相反的形式打印。 –

+0

@AhsanAsif這是因爲您將每個節點插入列表的頭部。你需要追加到列表的尾部。 –

+0

是的,正如@JohnnyMopp所說的,你將它們插入到頭部(基本上它會讓你的鏈表首先插入,而不是最後一個) – Hernantas