while 循环每次循环重复 cout 行两次吗?

do while loop repeating cout line twice every loop?

每次我 运行 我的程序,do while 循环的第一行中的输出会重复自己。所以输出"Enter characters to add..."在每次循环开始时输出两次。如何让它每次循环重复只输出一次?

主文件

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

}

问题出在这里ch = cin.get();。它会自动读取输入流中剩下的任何内容。您需要先用 this.

清理它

您的程序正在从标准输入缓冲区读取数据。阅读更多相关信息 “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 != '.');