每次运行程序时,do while循环第一行的输出都会重复。所以输出"输入要添加的字符......"在每个循环开始时输出两次。如何在每次循环重复时只输出一次?
主档
#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;
}
答案 0 :(得分:4)
问题在于ch = cin.get();
。它将自动读取输入流中剩余的内容。您需要先使用this清除它。
答案 1 :(得分:-1)
您的程序正在从标准输入缓冲区读取。阅读更多相关信息 &#34; What is the standard input buffer?&#34;
如果你想重复&#34; cout&#34;只有一次,重写如下:
char ch;
cout <<"char"<<ch<< "Enter characters to add, enter full stop to finish adding." << endl;
do {
ch = cin.get();
} while (ch != '.');