strcmp doesnt give 0, but the two args are the sam

2019-03-04 00:40发布

问题:

I can't see what I'm doing wrong.

void contains(NODE *head, char *user)
{
        NODE *this = head;
        while(this != NULL)
        {
            strcpy(temp, this->data);
//          printf("%s\n",user);
//          printf("%s\n",temp);
            printf("%d test\n", strlen(user));
            printf("%d node\n", strlen(temp));;
            printf("%d\n",strcmp(temp, user));
            if(strcmp(this->data, user) == 0){
                printf("Found data %s\n", this->data);
            }
            this = this->next;
        }
    }

And I have this in main (contains is called on the last line):

NODE *head;
    head = malloc(sizeof(NODE));

    bool headNode = true;
    char userID[1000];
    char userIDsearch[180];
    char test[180] = "monkey";
    while((fgets(userID,1000,stdin) != NULL)){
//      printf("%s\n", userID);
        if(headNode == true)
        {
            head = insert(NULL, userID);
            headNode = false; //this is used to insert data to my linked list for the first time
        }
        else
        {
            head = insert(head, userID);
        }
    }
    contains(head, test);

strcmp should be giving zero if I input "monkey", but it gives 1. Also, I tested and used strlen on both strings I am comparing, for some reason strlen gives length + 1 for temp (my input), but strlen gives the correct length for ~user` (which I set to the string "monkey").

回答1:

Don't forget that fgets() retains the newline, but you did not remove it, or add one to the end of test.

You would spot this if you printed the input using a statement such as:

printf("User ID <<%s>>\n", userID);

inside the loop. The << and >> show you where the string starts and ends, and would reveal the embedded newline.