Sample program involving linked lists and structs doesn't work [closed]

对着背影说爱祢 提交于 2019-12-12 03:28:47

问题


So, this is a sample program supplied by my prof. Its function is to search a linked list of trees and return a result of weather or not it found the tree input by the user. However, no matter what I input it always returns false. What's wrong with it?

#include <stdio.h>
#include <string.h>
#define NL 20

typedef struct tree 
{
    char tree_name [NL];
    struct tree* next;
}tree;

int 
checktree (tree *p, char name[])
{
   int found = 0;
   while (p != NULL)
   {
       if (strcmp(p -> tree_name, name) == 0)
          found = 1;
       p = p -> next;
   }
   return (found);
}


int
main (void)
{
    /* declaring variables to hold tree nodes */
    tree tree1, tree2, tree3, tree4;

    /* declaring the starting and traveling pointers */
    tree *p, *start;

    char treename[NL];

    /* putting tree names into each node */
    strcpy (tree1.tree_name, "Maple");
    strcpy (tree2.tree_name, "Fir");
    strcpy (tree3.tree_name, "Pine");
    strcpy (tree4.tree_name, "Oak");

    /* setting the start of the list at tree1 */
    start = &tree1;

    /* linking the other trees together */
    tree1.next = &tree2;
    tree2.next = &tree3;
    tree3.next = &tree4;

    /* sets tree4 as the last node of the list  */
    tree4.next = NULL;

    /* checking if a tree is in the list */
    printf ("Enter tree name to search: ");
    fgets (treename,sizeof(treename),stdin);

    if (checktree(start, treename))
       printf ("%s was found in our list of trees.\n", treename);
    else
       printf ("%s was not found in our list of trees.\n", treename);
    return (0);
}

回答1:


fgets reads a line that also includes the newline character. Add code to remove it before the call to checktree.

fgets (treename,sizeof(treename),stdin);
int len = strlen(treename);
if ( treename[len-1] == '\n' )
{
   treename[len-1] = '\0';
}

if (checktree(start, treename)) { ... }


来源:https://stackoverflow.com/questions/36341183/sample-program-involving-linked-lists-and-structs-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!