首页 > 解决方案 > 无法使用 char 正确显示链表

问题描述

记录标签.cpp

void recordLabel::addArtist(char* artistName)
    {
        Node* temp = new Node;                  
        temp->artistName = artistName;         
        temp->next = head;                     
        head = temp;                            
        
    }
    
    void recordLabel::displayArtists()
    {
        Node* tmp = head;
        tmp = tmp->next;
        while (tmp != NULL)
        {
            cout << tmp->artistName << " ";
            tmp = tmp->next;
        }
    }

Main.cpp

    int main()
    {
        recordLabel recordLabel;
        
        char* artistName = new char[25];
        char repeatLoop = 'y';
    
        while (repeatLoop == 'y' || repeatLoop == 'Y')
        {
            cout << "Please Enter an Artist Name: ";
            cin.getline(artistName,25);
    
            recordLabel.addArtist(artistName);
            
  
            cout << "Do you want to add a Name? (y/n): ";
            cin >> repeatLoop;
    
            cin.ignore();
        }
        
        recordLabel.displayArtists();
         
    
        //delete[] artistName;
        system("pause");
        return 0;
    }

所以我试图显示我的链接列表,但是当我输入像“john”“kyle”“david”这样的输入时,显示函数的输出最终是大卫大卫大卫。有人可以帮我弄这个吗?另外,我意识到使用字符串可以解决我的大部分问题,但我试图只使用字符。

谢谢

标签: c++linked-listdynamic-memory-allocationsingly-linked-listc-strings

解决方案


修改方法addArtist如下:

void recordLabel::addArtist(char* artistName)
{
    Node* temp = new Node;
    temp->artistName = strdup(artistName);
    temp->next = head;
    head = temp;
}

您还需要包括string.h

#include <cstring>

不要忘记使用析构函数清理内存


推荐阅读