【问题标题】:Same data but not equal inside two Nodes两个节点内的数据相同但不相等
【发布时间】:2017-02-12 14:56:56
【问题描述】:

当我比较两个节点内的数据时,它说它们不相等,但它们打印的信息相同。

while(currentUserTry != NULL && currentPassword != NULL) {

    if(currentUserTry->color != currentPassword->color){
        printf("user %s - %lu\n", currentUserTry->color, strlen(currentUserTry->color));
        printf("pass %s - %lu\n", currentPassword->color, strlen(currentPassword->color));
    }

    currentUserTry = currentUserTry->next;
    currentPassword = currentPassword->next;
}

打印:
用户 az - 2
通过 az - w
用户 vm - 2
通过 vm - 2

【问题讨论】:

  • 顺便说一句,让我们知道答案中提出的内容是否有效,方法是勾选接受,回答。如果没有任何效果,请在下面的答案中评论什么不起作用以及应该改变什么。

标签: c string-comparison


【解决方案1】:

比较两个字符串时使用strcmp

while(currentUserTry != NULL && currentPassword != NULL) {

    if(strcmp(currentUserTry->color, currentPassword->color)){
        printf("user %s - %lu\n", currentUserTry->color, strlen(currentUserTry->color));
        printf("pass %s - %lu\n", currentPassword->color, strlen(currentPassword->color));
    }

    currentUserTry = currentUserTry->next;
    currentPassword = currentPassword->next;
}

C 库函数 int strcmp(const char *str1, const char *str2) 将 str1 指向的字符串与 str2 指向的字符串进行比较。

该函数返回值如下:

如果返回值

如果返回值>0,则表示str2小于str1。

如果返回值=0,则表示str1等于str2。

【讨论】:

    【解决方案2】:

    在这个 if 语句中你必须使用标准的 C 函数 strcmp

    if( strcmp( currentUserTry->color, currentPassword->color ) != 0 ){
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      • 2022-01-14
      • 2020-08-03
      • 2015-01-01
      相关资源
      最近更新 更多