c++ - 字符串不会存储在链表中
问题描述
#include <iostream>
#include <string.h>
using namespace std;
class MovieList {
private:
struct MovieNode {
string title;
struct MovieNode *next;
};
MovieNode *head;
public:
void appendNode(string var);
void displayList();
};
void MovieList::appendNode(string var) {
MovieNode *newNode, *nodePtr;
newNode = new MovieNode;
newNode->title = var;
newNode->next = NULL;
if (!head) {
head = newNode;
}
else {
nodePtr = head;
while (nodePtr->next)
nodePtr = nodePtr->next;
nodePtr->next = newNode;
}
cout << endl << "Input has been successfull!" << endl;
}
void MovieList::displayList() {
MovieNode *nodePtr;
if (head == NULL) {
cout << "The list is empty!" << endl;
}
else {
cout << "The nodes in the List are... " << endl;
nodePtr = head;
while (nodePtr) {
cout << nodePtr->title << endl;
nodePtr = nodePtr->next;
}
}
}
int main() {
MovieList list;
string var;
cout << " << Enter Movie >> " << endl << endl;
cout << "Enter a movie: ";
getline(cin, var);
list.appendNode(var);
list.displayList();
}
我的问题是为什么字符串变量不会显示在显示空白中。当我尝试输入字符串时,代码开始工作,但随后退出程序而不显示我输入的内容。我如何放置字符串或者将字符串实现到节点中是否有问题?请帮忙,我是链表中的新手。
解决方案
一个问题是创建对象MovieList.head
时未初始化。MovieList
因此,当MovieList.append()
被调用时,这一行:
if (!head)
导致程序的行为不稳定,因为head
指针是任何值,您不知道该值是什么。它可能是nullptr
,因此程序可以工作,但它可能是任何其他值。
底线是您应该在创建对象时初始化您的成员变量。您可以创建一个已初始化的默认构造函数head
,也可以head
在声明点直接内联初始化:
class MovieList
{
private:
struct MovieNode
{
string title;
struct MovieNode *next;
};
MovieNode *head;
public:
MovieList() : head(nullptr) {} // Using constructor
void appendNode(string var);
void displayList();
};
或者:
class MovieList
{
private:
struct MovieNode
{
string title;
struct MovieNode *next;
};
MovieNode *head = nullptr; // Initialized here
public:
void appendNode(string var);
void displayList();
};
推荐阅读
- z3 - 微软Z3解决方案格式理解
- matlab - MATLAB 中的傅里叶描述符
- python - 当 Python Thrift 解码由结构索引的映射时如何避免“TypeError:unhashable type”
- ios - 如何在 Swift 中平滑 100%
- python - 添加数据时从数据框中删除列表
- flutter - 如何在 Flutter 中更新 ModalBottomSheet 的状态?
- javascript - 通过将按钮添加到数据库中从新创建的输入字段中获取数据的问题
- python - 使用 Python 读取 YAML 文件会导致 yaml.scanner.ScannerError: mapping values are not allowed here
- java - 使用来自json数组的java spark sql将表保存在hive中
- c - math.h 中的函数日志返回错误