2017-01-27 9 views
0

프로그램을 실행할 때마다 do while 루프의 첫 번째 줄에 출력이 반복됩니다. 따라서 "Enter characters to add ..."출력은 각 루프의 시작에서 두 번 출력됩니다. 루프 반복마다 한 번만 출력하도록하려면 어떻게합니까?do while loop 반복마다 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 != '.');