Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C the output is wrong

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading