2017-01-27 88 views
0

每次運行我的程序時,do while循環的第一行中的輸出都會重複出現。因此,輸出「輸入要添加的字符...」在每個循環的開始處輸出兩次。每次循環重複如何讓它只輸出一次?while while循環每次循環重複兩次cout行?

主文件

#include "LinkedList.h" 
#include "ListNode.h" 
#include "Node.h" 
#include <iostream> 
#include <stdlib.h> 
using namespace std; 

LinkedList<char> *setUpSentence() { 
    //allocate the linked list objet 
    LinkedList<char> *sentence = new LinkedList<char>(); 
    char ch; 
    do { 
     cout << "Enter characters to add, enter full stop to finish adding." << endl; 
     ch = cin.get(); 
     sentence->addAtEnd(ch); 
    } while (ch != '.'); 

    return sentence; 
} 

int main() { 

    //call the function, store the returned pointer in sentence variable 
    LinkedList<char> *sentence = setUpSentence(); 

    while(sentence->size > 0) { 
     cout << sentence->removeAtFront() << endl; 
    } 
    //delete to avoid memory leak 
    delete sentence; 

} 
+3

無關:'LinkedList的 *句子=新的LinkedList ();'是不必要的,只需使用'LinkedList 句子;'而不是後來按值返回它。 –

+7

''\ n''是一個字符。 – melpomene

+1

關於您的實際問題:請[編輯]您的問題以提供[mcve]。 –

回答

4

的問題是在這裏ch = cin.get();。它會自動讀取輸入流中剩下的任何內容。您需要先用this清理它。

-1

您的程序正在從標準輸入緩衝區讀取。閱讀 更多關於這個 「What is the standard input buffer?

如果你想重複 「COUT」 只有一次,如下改寫:

char ch; 
cout <<"char"<<ch<< "Enter characters to add, enter full stop to finish adding." << endl; 
do { 
    ch = cin.get(); 
} while (ch != '.');