【问题标题】:strcmp doesnt give 0, but the two args are the samestrcmp 不给 0,但是两个 args 是一样的
【发布时间】:2014-02-04 04:21:20
【问题描述】:

我看不出我做错了什么。

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;
        }
    }

我在 main 中有这个(包含在最后一行调用):

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);

如果我输入“monkey”,strcmp 应该给出零,但它给出 1。此外,我在比较的两个字符串上测试并使用了 strlen,出于某种原因,strlen 为 @ 给出长度 + 1 987654327@(我的输入),但strlen 给出了 ~user` 的正确长度(我将其设置为字符串“monkey”)。

【问题讨论】:

标签: c debugging pointers strcmp


【解决方案1】:

不要忘记fgets() 保留了换行符,但你没有删除它,或者在test 的末尾添加一个。

如果您使用以下语句打印输入,您会发现这一点:

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

在循环内。 &lt;&lt;&gt;&gt; 显示字符串的开始和结束位置,并显示嵌入的换行符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多