Qball Qball - 4 years ago 147
C Question

strcmp does not return 0 on equal strings in c

So im making a program that checks if a word is a palindrome but when it comes to comparing the final strings at the end even if they are the same i get a -1 result edit: copy pasted the exact same code i used


int main()

char input[50];
char test[50];

int ret;

printf("Enter word or phrase to compare ");


ret = strcmp(test,input);

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

printf("\n this is not a palindrome");

For input i used "ala" which i know is a palindrome i get the result

this is not a palindrome

Demonstration on IDEONE.

jxh jxh
Answer Source

The problem is that you call strrev without stripping off the newline from your input obtained from fgets. This causes your reversed string to have the newline at the beginning of the string, which would cause a mismatch even if you intended to provide a palindrome as the input.

While there are various ways to achieve this, one way would be to look at the last byte of your input, and see if it is a newline character. If it is, remove it.

if (fgets(input,sizeof(input),stdin) == NULL) {
    /* todo: ... handle error ... */
    return 0;
len = strlen(input);
if (input[len-1] == '\n') input[--len] = '\0';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download