c++ - 无法使用 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”这样的输入时,显示函数的输出最终是大卫大卫大卫。有人可以帮我弄这个吗?另外,我意识到使用字符串可以解决我的大部分问题,但我试图只使用字符。
谢谢
解决方案
修改方法addArtist
如下:
void recordLabel::addArtist(char* artistName)
{
Node* temp = new Node;
temp->artistName = strdup(artistName);
temp->next = head;
head = temp;
}
您还需要包括string.h
#include <cstring>
不要忘记使用析构函数清理内存
推荐阅读
- javascript - 将数据数组从表单传递到 ajax 到 PHP 发布文件
- php - 在 Laravel 5.7 中看不到 Flash 消息
- arrays - 在numpy中切片列集
- c# - 如何使用 OpenXml 和 c# 从范围中获取所有行/单元格值
- python - 替换元素 np 数组
- java - 什么是 Spring Boot 的 @Assisted 版本
- entity-framework - 我没有 EF CORE,但 Entity Framework Core 和 Entity Framework 6 都安装了
- php - 我正在尝试搜索和显示数据,如果可能的话,在另一个页面中
- python - Python - 如何根据嵌套字典中的值返回字典键?
- macos - 重置 macOS 应用程序安全警报