我正在尝试创建一个充满字符的链接列表。以下代码仅保存其他所有元素,我可以修改如何解决此问题?附件是用户阅读输入中使用的两个功能。
void LList :: InsertTail(element thing) {
// PRE : the N.O. LList is valid
// POST : the N.O. LList is unchanged, except that a
// new listnode containing element thing has been
// inserted at the tail end of the list
listnode * temp;
temp = new listnode;
temp -> data = thing;
temp -> next = NULL;
if(head == NULL)
head = temp;
else
tail -> next = temp;
tail = temp;
}
void LList :: ReadForward() {
// PRE: the N.O. LList is valid
// POST : the N.O. LList is valid, all of its
// previous listnodes have been deleted, and
// it now consists of new listnodes containing
// elements given by the user in foward order
char userval;
Clean();
cout << "Enter the message: ";
userval = cin.get();
cout << userval;
while (cin.get()!= SENTINEL) {
InsertTail(userval);
userval = cin.get();
cout << userval;
}
cin.clear();
cin.ignore(80, 'n');
}
问题是您的读书。
每次致电CIN.Get()您正在阅读另一个字符 - 因此跳过该角色而被添加。
将其更改为:
while(userval) {
问题在您的while()
循环中ReadForward()
方法:
while (cin.get() != SENTINEL) { <----
InsertTail(userval);
userval = cin.get();
cout << userval;
}
在标记的行上,您调用cin.get()
,但切勿将其存储在任何地方。这会丢弃所有其他字符,因为您只是在读之后仅存储一个字符。
修复程序是每次运行循环时都会在userval
内存储get()
的结果。
cout << "Enter the message: ";
while (cin >> userval) {
cout << userval;
InsertTail(userval);
}