链表显示垃圾字符
Linked list displays garbage characters
不知道为什么,但每次我显示链表时,它只显示垃圾字符。当我将_getche
添加到第 31 行并在第 53 行显示值时,会出现此问题,并带有_putch(current->c);
如果有人可以帮助描述我的问题是什么并提供一个解决方案,将不胜感激!
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
class ListNode
{
public:
char c;
ListNode *next;
};
int main()
{
ofstream outputFile;
ListNode *current;
ListNode *start;
ListNode *newNode = new ListNode();
current = nullptr;
start = newNode;
newNode->next = nullptr;;
cout << "Hit 'esc' when you are done.n";
while (newNode->c = _getche() != 27)
{
//If start is empty, create node
if (current == nullptr)
{
current = newNode;
}
else //If start is not empty, create new node, set next to the new node
{
current->next = newNode;
current = newNode;
}
newNode = new ListNode();
newNode->next = nullptr;
}
//Display linked list
cout << "Here is what you have typed so far:n";
current = start;
while (current != nullptr)
{
_putch(current->c);
current = current->next;
}
cout << endl;
outputFile.close();
system("pause");
return 0;
}
在:
while (newNode->c = _getche() != 27)
=
的优先级低于!=
,因此它将_getche() != 27
的结果分配给newNode->c
。
修复:
while((newNode->c = _getche()) != 27)
通过维护指向最后一个节点的next
指针(使用head
初始化ptail
指针,可以更轻松地追加单向链表:
ListNode *head = nullptr, **ptail = &head;
cout << "Hit 'esc' when you are done.n";
for(char c; (c = _getche()) != 27;) {
auto node = new ListNode{c, nullptr}; // allocate and initialize a new node
*ptail = node; // append to the end of the list
ptail = &node->next; // move the end of list to the new node
}
//Display linked list
cout << "Here is what you have typed so far:n";
for(auto next = head; next; next = next->next)
_putch(next->c);
相关文章:
- 字符串-C++后显示的随机字符
- 显示基于用户输入的整数的字符
- 在将字符插入 2d 字符串时如何不显示空字符?
- 为什么strlen(s)与s的大小不同,为什么cout-char显示的是字符而不是数字
- 为什么C++在将浮点数转换为字符时没有显示缩小转换错误?
- 链表显示垃圾字符
- 在大小为 10 的 char 数组中输入超过 10 个字符的字符串并输出时,它会显示整个数组而不是前 10 个数组.为什
- 程序,它接受用户输入的字符并按出现的降序显示它们
- 使用带有诅咒库的 stdscr 创建窗口,在边框而不是线条中显示不需要的笑脸字符
- 如何检查输入是否为字符并显示它是"invalid input",否则它将按原样运行
- 如何在不将其转换为 ASCII 字符的情况下显示 QByteArray 的十六进制值
- 如何从显示板将字符显示为字符串?
- 将终端设置为原始模式:仅在按下下一个键后显示字符
- 在QLineEdit中显示和编辑转义字符
- 我的程序没有将字符显示在屏幕上
- C++控制台字符显示
- C++特殊字符显示为"?"
- 将字符显示为没有显式强制转换的整数
- 为什么sizeof为一个字符显示4个字节
- 使用'uxxxx'格式定义的字符显示错误的字符