C the output is wrong

Advertisements

output expression is not correct

code :

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

int main() {
    char a[40],b[40];
    printf("character input: "); fgets(a, sizeof(a), stdin);
    strcpy(b, a);
    strrev(a);
    printf("%s\n", a);
    printf("%s", b);
    
    if (b == a) printf("palindrome");
    else printf("not palindrome");
}

character input:

seles

output:

seles
seles
not palindrome

>Solution :

The function fgets can append to the entered string the new line character '\n' that corresponds to the pressed key Enter provided that the destination character array has space to store it.

You need to remove it like for example

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

before reversing the string.

Also in this if statement

if (b == a) printf("palindrome");

there are compared two pointers that point to first characters of the strings instead of the strings themselves. Instead you need to write using standard C function strcmp

if ( strcmp( b, a ) == 0 ) puts("palindrome");
else puts("not palindrome");

Leave a Reply Cancel reply