-1

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

#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");
}

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

this is not a palindrome

Demonstration on IDEONE.

jxh
  • 69,070
  • 8
  • 110
  • 193
Qball
  • 27
  • 2

1 Answers1

1

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';
strcpy(test,input);
jxh
  • 69,070
  • 8
  • 110
  • 193
  • Actually, this question was [asked before](http://stackoverflow.com/q/20183687/315052). – jxh Feb 07 '17 at 22:28