strcmp 在 c 中的相等字符串上不 return 0

strcmp does not return 0 on equal strings in c

所以我正在制作一个程序来检查一个单词是否是回文,但是当涉及到比较最后的字符串时,即使它们相同,我得到一个 -1 结果编辑:复制粘贴完全相同的代码我用过

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

int main()
{
    char input[50];
    char test[50];

    int ret;

    printf("Enter word or phrase to compare ");
    fgets(input,sizeof(input),stdin);
    strcpy(test,input);

    strrev(input);

    ret = strcmp(test,input);

    if(ret == 0)
        printf("\n this is a palindrome ");
    else
        printf("\n this is not a palindrome");
}

对于输入,我使用了 "ala",我知道这是一个回文,我得到了结果

this is not a palindrome

Demonstration on IDEONE.

问题是您调用 strrev 时没有从从 fgets 获得的输入中剥离换行符。这会导致您的反向字符串在字符串的开头具有 newline,即使您打算提供回文作为输入,这也会导致不匹配。

虽然有多种方法可以实现这一点,但一种方法是查看输入的最后一个字节,看看它是否是换行符。如果是,请将其删除。

if (fgets(input,sizeof(input),stdin) == NULL) {
    /* todo: ... handle error ... */
    return 0;
}
len = strlen(input);
if (input[len-1] == '\n') input[--len] = '[=10=]';
strcpy(test,input);