Thread: C Palindrome problem

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    2

    Unhappy C Palindrome problem

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <conio.h>
    
    int main()
    {
    	char x[26];
    	char y[26];
    
    	clrscr();
    	printf("Enter String: \n");
    
    	fgets( x, 26, stdin);
    
    	strcpy( y, x);
    	strrev( y );
    
    		if (strcmp( y, x) == 0)
    			printf("%s is palindrome", x);
    		else
    			printf("%s is not palindrome", x);
    
    	getch();
    	return 0;
    }
    Its output is always "not palindrome".
    It works on gets() but I want to use fgets() instead.
    Help please. Anyone?

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Don't forget that strcmp is case sensitive... If you put in "Bob" it's not a palendrome but "bob" is. To avoid the problem you can use strupper() to make sure it's all upper case before reversing...

  3. #3
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Take note that strrev(), strupper() are non-standard function.

  4. #4
    Registered User baffleddreams's Avatar
    Join Date
    Aug 2010
    Location
    India
    Posts
    15
    i think fgets()
    is used to get a file....also a string....try only with gets ....cos fgets() has a lot of code writtern behind it(same is the case with scanf() )

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    The thing about fgets() is that it appends \n to the buffer if there is room to add it.

    For simple cases, the palindrome of "bob\n" would be "\nbob", but that can never be a valid result from fgets().

    See the FAQ for how to remove the \n from a buffer returned by fgets()
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Oct 2010
    Posts
    2
    I see, Thank you guys. You all have been helpful, I'll get back if I came up with something. Cheers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Palindrome, problem with isalpha
    By Kyeong in forum C Programming
    Replies: 2
    Last Post: 11-07-2008, 01:28 PM
  2. Memory problem with Borland C 3.1
    By AZ1699 in forum C Programming
    Replies: 16
    Last Post: 11-16-2007, 11:22 AM
  3. Someone having same problem with Code Block?
    By ofayto in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2007, 08:38 AM
  4. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  5. WS_POPUP, continuation of old problem
    By blurrymadness in forum Windows Programming
    Replies: 1
    Last Post: 04-20-2007, 06:54 PM