2016-12-01 57 views
0

我想創建一個充滿字符的鏈表。以下代碼僅保存其他所有元素,我可以修改哪些內容以解決此問題?附件是用於讀取用戶輸入的兩種功能。C++鏈表只輸出每隔一個元素

void LList :: InsertTail(element thing) { 
     // PRE : the N.O. LList is valid 
     // POST : the N.O. LList is unchanged, except that a 
     //  new listnode containing element thing has been 
     //  inserted at the tail end of the list 

     listnode * temp; 

     temp = new listnode; 

     temp -> data = thing; 
     temp -> next = NULL; 
     if(head == NULL) 
       head = temp; 
     else 
       tail -> next = temp; 
     tail = temp; 
} 






void LList :: ReadForward() { 
     // PRE: the N.O. LList is valid 
     // POST : the N.O. LList is valid, all of its 
     //  previous listnodes have been deleted, and 
     //  it now consists of new listnodes containing 
     //  elements given by the user in foward order 
     char userval; 
     Clean(); 
     cout << "Enter the message: "; 
     userval = cin.get(); 
     cout << userval; 
     while (cin.get()!= SENTINEL) { 
       InsertTail(userval); 
       userval = cin.get(); 
       cout << userval; 
     } 
     cin.clear(); 
     cin.ignore(80, '\n'); 

} 

回答

1

問題是您在ReadForward中的whileloop。

每次調用cin.get()時,您正在讀取另一個字符 - 因此會跳過添加該字符。

將其更改爲:

while(userval) { 
0

的問題是在ReadForward()方法內您while()循環:

while (cin.get() != SENTINEL) { <---- 
    InsertTail(userval); 
    userval = cin.get(); 
    cout << userval; 
} 

在你打電話cin.get(),但從來沒有存儲任何地方標線。這會丟棄所有其他字符以免被閱讀,因爲您只是在之後存儲了一個字符,您已經閱讀了另一個字符。

修復方法是在每次循環運行時將get()的結果存儲在userval之內。

cout << "Enter the message: "; 
while (cin >> userval) { 
    cout << userval; 
    InsertTail(userval); 
} 
相關問題