0

Every time I run my program, the output in the first line of the do while loop repeats itself. So the output "Enter characters to add..." is output twice at the start of each loop. How do I make it only output once every loop repetition?

main file

#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;

}
Rama
  • 3,222
  • 2
  • 11
  • 26
Liam
  • 429
  • 1
  • 13
  • 33

2 Answers2

4

The problem is in here ch = cin.get();. It will automatically read whatever left in the input stream. You need to clean it first with this.

Community
  • 1
  • 1
cuongptnk
  • 472
  • 3
  • 15
-1

Your program is reading from standard input buffer. Read more about this in "What is the standard input buffer?"

If you wish to repeat "cout" only once, rewrite it as follows:

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