Lawrence Wong
Lawrence Wong

Reputation: 1139

C Output formatting issues

I have some problems on the formatting of my output in C. Please see the image below for my output

See image

I want my output to be as follow

Enter word: KayaK

Kayak is a palindrome.

    // palindrome.c
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
    #define MAXLEN 20

    int isPalindrome(char [], int);

    int main(void) {
    char word[MAXLEN+1];
    int size;

    printf("Enter word: ");
    fgets(word,MAXLEN+1,stdin);
    size = strlen(word);
    if (isPalindrome(word, size-1)) //size - 1 because strlen includes \0
   {
    printf("%s is a palindrome.\n",word);
   }
   else
   {
    printf("%s is not a palindrome.\n",word);
   }
   return 0;
   }

 int isPalindrome(char str[], int size) {
int i;
for (i = 0; i < size; i++)
{
    if (tolower(str[i]) != tolower(str[size - i - 1]))
    {
        return 0;
    }
}
return 1;
}

Upvotes: 1

Views: 150

Answers (3)

Aniket Inge
Aniket Inge

Reputation: 25705

to strip it means to remove it from the string.

//...
printf("Enter word: ");
fgets(word,MAXLEN+1,stdin);
size = strlen(word);
word[size-1] = '\0'
//program

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Your code masks the problem of the original string containing an end-of-line marker:

This line chops off the trailing zero

if (isPalindrome(word, size-1)) //size - 1 because strlen includes \0

The comment is wrong, by the way: strlen does not include the \0, it includes \n.

This line ignores the trailing \n because of size - i - 1 subtracts 1 again, even though you have subtracted it when you first called the function:

if (tolower(str[i]) != tolower(str[size - i - 1]))

You should do this:

size--;
word[size] = '\0';
if (isPalindrome(word, size-1)) //size - 1 because strlen includes \0

Now you can correct your palindrome checker as follows:

if (tolower(str[i]) != tolower(str[size - i])) // No "minus one"
{
    return 0;
}

Upvotes: 1

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143091

fgets reads the string, including terminating newline. Just strip it before further processing.

Note, that you actually take this into account, when passing size-1, but for the wrong reason. It includes \n, not \0.

Upvotes: 8

Related Questions