c++ - 链表显示乱码

标签 c++ visual-studio linked-list visual-studio-2017 c++17

不知道为什么,但每次我显示链接列表时,它只显示乱码。当我将 _getche 添加到第 31 行,并使用 _putch(current->c); 在第 53 行显示值时发生此问题 如果有人可以帮助描述我的问题是并提供一个解决方案,我们将不胜感激!

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

= 有较低的 precedence !=,因此它将 _getche() != 27 的结果分配给 newNode->c

修复:

while((newNode->c = _getche()) != 27)

通过维护 ptail 指向最后一个节点的 next 指针,用 head 初始化,可以更容易地追加单链表:

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++ - 链表显示乱码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52451833/

相关文章:

c++ - IF 内有两个语句的简写 If/Else 语句

c++ - 从另一个模板结构继承的模板结构

c++ - Havok 退出析构函数中的调用导致未处理的异常

c# - 无法在 Visual Studio (Mac) 上使用 .NET Core 3.1 创建 Web 应用

wpf - Windows 10 所有 DPI 设置上的所有图标分辨率?格式?像素艺术作为图标?开始菜单中等磁贴中的大尺寸图标?

c++ - 我的 $Foo ATL 解决方案中的 ($Foo)PS 项目有什么用?

c++ - 将元素添加到已排序的链表

c++ - 这个 _com_ptr_t move 分配有什么目的吗?

java - Java 中 ArrayList 和 LinkedList 的区别——性能的原因

c - Readdir() 结果添加到链表导致段错误