【问题标题】:Linked list displays garbage characters链表显示乱码
【发布时间】:2018-09-21 22:43:18
【问题描述】:

不知道为什么,但每次我显示链接列表时,它只会显示垃圾字符。当我将_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;
}

【问题讨论】:

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


    【解决方案1】:

    在:

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

    =precedence 低于!=,因此它将_getche() != 27 的结果分配给newNode-&gt;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);
    

    【讨论】:

      猜你喜欢
      • 2019-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      • 2021-06-14
      • 2013-04-03
      • 2013-09-20
      相关资源
      最近更新 更多