C: 使用 strcmp

C: Working with strcmp

作为初学者,我一直在使用库 string.h 的一些函数,并且对函数 strcmp.

有一些疑问

我写了比较两个字符串的程序。如果它们相等,则 returns YES 否则 NO

#include <stdio.h>
#include <string.h>

int main() {

    char a[100];
    char b[15] = "hello";

    fgets(a, 100, stdin);

    int compare;

    compare = strcmp(a, b);

    if(compare == 0) {

        printf("YES");
    }
    else {

        printf("NO");
    }

    return 0;
}

在 运行 之后,即使我从键盘输入 hello,我也会得到 NO。当我添加行 printf("%d", compare) 时,结果是对于任何输入我得到一个 1,也就是说,a 中的停止字符大于 b 中的停止字符。

我的错误在哪里?

fgets(a, 100, stdin); 也将您输入的换行符存储到缓冲区中。因此 a 包含 "hello\n"。那个额外的字符抵消了比较。

您可以尝试通过某种方式删除换行符1,或者与 strncmp 进行比较。


  1. 例如:

    char *newline = strchr(a, '\n');
    if (newline)
      *newline = '[=10=]';
    

这样扫描并没有错误,但问题是,fgets() 扫描并将尾随换行符存储到提供的缓冲区中。如果您将缓冲区与不包含终止换行符的字符串文字进行比较,则需要摆脱它。

要去除尾随的换行符,您可以使用类似

的东西
size_t len = strlen(a);
if (len > 0 && a[len-1] == '\n') {
    a[--len] = '[=10=]';
}

See this answer for more reference

不去掉换行符,strcmp()不会宣布比​​较成功。

否则,您可以使用 strncmp() 并提供字符串文字的大小,以将比较限制在 有效 输入。

如果源数组中有足够的 space,

fgets 附加对应于 Enter 键的换行符。

您应该在按照以下方式将字符串与另一个字符串进行比较之前删除该字符

a[strcspn( a, "\n" )] = '[=10=]';

例如

#include <stdio.h>
#include <string.h>

int main() {

    char a[100];
    char b[15] = "hello";

    fgets(a, 100, stdin);

    a[strcspn( a, "\n" )] = '[=11=]';

    int compare;

    compare = strcmp(a, b);

    if(compare == 0) {

        printf("YES");
    }
    else {

        printf("NO");
    }

    return 0;
}