【发布时间】:2014-08-29 19:32:41
【问题描述】:
我正在尝试使用来自方法的字符串输入并将其设置为结构的变量,然后我将其放入链接列表中。我没有包括所有代码,但我确实发布了构造函数和所有这些好东西。现在代码正在中断
node->title = newTitle;
node->isbn = newISBN;
所以 newTitle 是来自我试图设置为变量节点的 Book 结构的标题变量的方法的字符串输入。现在,我假设这与指针问题并试图为它们设置数据有关,但我无法找到修复/替代方案。 另外,我尝试使用
strcpy(node->title, newTitle)
但这在将字符串转换为字符列表时存在问题,因为 strcpy 仅使用字符列表。还尝试了其他一些方法,但似乎都没有成功,我们将不胜感激。
struct Book
{
string title;
string isbn;
struct Book * next;
};
//class LinkedList will contains a linked list of books
class LinkedList
{
private:
Book * head;
public:
LinkedList();
~LinkedList();
bool addElement(string title, string isbn);
bool removeElement(string isbn);
void printList();
};
//Constructor
//It sets head to be NULL to create an empty linked list
LinkedList::LinkedList()
{
head = NULL;
}
//Description: Adds an element to the link in alphabetical order, unless book with
same title then discards
// Returns true if added, false otherwise
bool LinkedList::addElement(string newTitle, string newISBN)
{
struct Book *temp;
struct Book *lastEntry = NULL;
temp = head;
if (temp==NULL) //If the list is empty, sets data to first entry
{
struct Book *node;
node = (Book*) malloc(sizeof(Book));
node->title = newTitle;
node->isbn = newISBN;
head = node;
}
while (temp!=NULL)
{
... //Rest of Code
【问题讨论】:
-
你在哪里学习?看起来这是“带字符串的 C”,而不是 C++。例如,您不需要使用 struct 关键字在结构的指针声明前加上
Book* temp;(最好也带有初始化)。也几乎没有理由使用malloc而不是new。 -
我没有那么优秀的 C 和 C++ 老师(他确实告诉我们他放在板上的代码无法在编译器上正确运行)而我没有了解 c++ 的许多“正确”或更新的声明
标签: string visual-c++ linked-list structure