【问题标题】:Elements not being added to Linked List [closed]未添加到链接列表的元素[关闭]
【发布时间】:2016-10-06 11:32:47
【问题描述】:

我无法将元素添加到我的链接列表中。我已经能够验证 char 字符串是否在 main() 中被正确扫描以及被复制到临时节点但是这没有被添加到链表中。

struct node{
    char string[MAX_STRING_LENGTH];
    node *next;
};

void insertAsFirstElement(node *head, node *last, char string[MAX_STRING_LENGTH])
{

    //create temporary node
    node *temp = new node;

    printf("The temp's string before copy is %s.\n", temp->string);
    //this is the string copy from the user to the temp
    strcpy(temp->string, string);

    printf("The temp's string is %s.\n", temp->string);

    //set the next pointer to NULL (points to nothing)
    temp->next = NULL;
    //set first value in list to temp
    head = temp;
    //set last value to temp
    last = temp;
}

【问题讨论】:

  • 欢迎来到 SO!请参考以下link 了解如何提出一个好的问题。当您只转储所有代码时,很难看出问题出在哪里。
  • C 和 C++ 是不同的语言。这是 C++,不是 C!你只是将 C 编码风格混合到 C++ 中,这是一个非常糟糕的主意。
  • 我同意蒂姆和奥拉夫的观点。您不应该混合使用 C 和 C++。国际海事组织 Tim 提出的良好解决方案。

标签: c++ c arrays string linked-list


【解决方案1】:
//this is the string copy from temp to new
char *strcpy(char *temp, const char string);

声明strcpy 函数。你想调用它。

strcpy(temp->string, string);

请不要混合搭配 C 和 C++。它们是非常不同的语言。如果您想在 C++ 中执行此操作,那么这非常容易。

#include <string>
#include <list>

int main() {
    std::list<std::string> strings;
    char choice = menu();

    while (choice != '4') {
        switch (choice) {
        case '1':
            std::string input;
            std::cout << "Please enter a string: ";
            std::cin >> input;
            strings.push_back(input);
            break;
        case '2':
            strings.pop_front();
            break;
        case '3':
            if (strings.size() == 0) {
                std::cout << "The list is empty.\n";
            } else {
                for (auto &s : strings) {
                    std::cout << s << "\n";
                }
            }
            break;
        default:
            std::cout << "System Exit";
            return 0;
        }
    }
}

【讨论】:

  • 这个答案无助于理解他发布的代码有什么问题。
  • @TaylorFlores 对不起。我想我有一个复制粘贴错误。现在应该修好了。
【解决方案2】:

您发布的代码存在一些问题。

第一个是你的链表不包含字符串,它包含一个指针数组。

您应该在char *string[MAX_STRING_LENGTH]; 中省略*

第二个是您致电scanf

scanf("%s\n", &amp;string[MAX_STRING_LENGTH]);

这会将程序用户的输入放入字符串之后的内存中。 那不是你想要的。您希望用户的输入在字符串的开头进入内存,如下所示:

scanf("%s\n", &amp;string[0]);

或者写得更简单:

scanf("%s\n", string);

最后,您没有将字符串复制到链表。 您可以使用strcpy 来做到这一点,如下所示:

strcpy(temp-&gt;string, string);

【讨论】:

  • 测试scanf的返回值以确保读取和处理了一个值也是一件好事。
  • 感谢您的回答。我修复了你注意到的所有问题。我还检查了 scanf 的值,并确认它正在扫描字符串并将这个字符串复制到临时文件中。到达那一点之后,它似乎不想向链接列表添加任何内容。
猜你喜欢
  • 2020-04-14
  • 2017-09-09
  • 2012-09-25
  • 2021-02-12
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多